Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(ui): Support multi knowledgebases operation

wizardchen91e65d6445a9
diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml
index d7c121d11..aef205fe2 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 b8d414a6b..dde85f429 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 d739a835a..4caa32c64 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 5a9c93bdb..7cdc14922 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 4fe476729..85efb6a50 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<RegisterResponse>
/**
* 获取当前用户信息
*/
-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 32f0b1721..2d5fe315f 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 f7d8dae97..26cb4901d 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 c42f1483b..4231cdb9b 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<any> {
+
+// 根据知识库ID执行配置更新
+export function initializeSystemByKB(kbId: string, config: InitializationConfig): Promise<any> {
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<DownloadTask[]> {
});
}
-// 获取当前系统配置
-export function getCurrentConfig(): Promise<InitializationConfig & { hasFiles: boolean }> {
+
+export function getCurrentConfigByKB(kbId: string): Promise<InitializationConfig & { hasFiles: boolean }> {
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 557a209e8..e507d332b 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<string> {
- // 如果设置中没有知识库ID,则使用测试数据
- await loadTestData();
- const testData = getTestData();
- if (!testData || testData.knowledge_bases.length === 0) {
- throw new Error('没有可用的知识库');
- }
-
- return testData.knowledge_bases[0].id;
-}
-
-export async function uploadKnowledgeBase(data = {}) {
- const kbId = await getDefaultKnowledgeBaseId();
+import { get, post, put, del, postUpload, getDown } from "../../utils/request";
+
+// 知识库管理 API(列表、创建、获取、更新、删除、复制)
+export function listKnowledgeBases() {
+ return get(`/api/v1/knowledge-bases`);
+}
+
+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 000000000..41011011e
--- /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 ef99e4558..000000000
--- 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<boolean> 是否成功加载
- */
-export async function loadTestData(): Promise<boolean> {
- // 如果已经加载过,直接返回
- 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 afb55ca59..d5ca73bc7 100644
--- a/frontend/src/components/menu.vue
+++ b/frontend/src/components/menu.vue
@@ -1,25 +1,48 @@
<template>
<div class="aside_box">
- <div class="logo_box">
+ <div class="logo_box" @click="router.push('/platform/knowledge-bases')" style="cursor: pointer;">
<img class="logo" src="@/assets/img/weknora.png" alt="">
</div>
<!-- 上半部分:知识库和对话 -->
<div class="menu_top">
<div class="menu_box" :class="{ 'has-submenu': item.children }" v-for="(item, index) in topMenuItems" :key="index">
- <div @click="gotopage(item.path)"
+ <div @click="handleMenuClick(item.path)"
@mouseenter="mouseenteMenu(item.path)" @mouseleave="mouseleaveMenu(item.path)"
- :class="['menu_item', item.childrenPath && item.childrenPath == currentpath ? 'menu_item_c_active' : item.path == currentpath ? 'menu_item_active' : '']">
+ :class="['menu_item', item.childrenPath && item.childrenPath == currentpath ? 'menu_item_c_active' : isMenuItemActive(item.path) ? 'menu_item_active' : '']">
<div class="menu_item-box">
<div class="menu_icon">
- <img class="icon" :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'setting' ? settingIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'tenant' ? tenantIcon : prefixIcon)" alt="">
+ <img class="icon" :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'tenant' ? tenantIcon : prefixIcon)" alt="">
+ </div>
+ <span class="menu_title" :title="item.path === 'knowledge-bases' && kbMenuItem ? kbMenuItem.title : item.title">{{ item.path === 'knowledge-bases' && kbMenuItem ? kbMenuItem.title : item.title }}</span>
+ <!-- 知识库切换下拉箭头 -->
+ <div v-if="item.path === 'knowledge-bases' && isInKnowledgeBase"
+ class="kb-dropdown-icon"
+ :class="{
+ 'rotate-180': showKbDropdown,
+ 'active': isMenuItemActive(item.path)
+ }"
+ @click.stop="toggleKbDropdown">
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
+ <path d="M2.5 4.5L6 8L9.5 4.5H2.5Z"/>
+ </svg>
+ </div>
+ </div>
+ <!-- 知识库切换下拉菜单 -->
+ <div v-if="item.path === 'knowledge-bases' && showKbDropdown && isInKnowledgeBase"
+ class="kb-dropdown-menu">
+ <div v-for="kb in initializedKnowledgeBases"
+ :key="kb.id"
+ class="kb-dropdown-item"
+ :class="{ 'active': kb.name === currentKbName }"
+ @click.stop="switchKnowledgeBase(kb.id)">
+ {{ kb.name }}
</div>
- <span class="menu_title">{{ item.title }}</span>
</div>
<t-popup overlayInnerClassName="upload-popup" class="placement top center" content="上传知识"
placement="top" show-arrow destroy-on-close>
- <div class="upload-file-wrap" @click="uploadFile" variant="outline"
- v-if="item.path == 'knowledgeBase'">
+ <div class="upload-file-wrap" @click.stop="uploadFile" variant="outline"
+ v-if="item.path === 'knowledge-bases' && $route.name === 'knowledgeBaseDetail'">
<img class="upload-file-icon" :class="[item.path == currentpath ? 'active-upload' : '']"
:src="getImgSrc(fileAddIcon)" alt="">
</div>
@@ -55,14 +78,14 @@
<!-- 下半部分:账户信息、系统设置、退出登录 -->
<div class="menu_bottom">
<div class="menu_box" v-for="(item, index) in bottomMenuItems" :key="'bottom-' + index">
- <div @click="gotopage(item.path)"
+ <div @click="handleMenuClick(item.path)"
@mouseenter="mouseenteMenu(item.path)" @mouseleave="mouseleaveMenu(item.path)"
- :class="['menu_item', item.childrenPath && item.childrenPath == currentpath ? 'menu_item_c_active' : item.path == currentpath ? 'menu_item_active' : '']">
+ :class="['menu_item', item.childrenPath && item.childrenPath == currentpath ? 'menu_item_c_active' : (item.path == currentpath) ? 'menu_item_active' : '']">
<div class="menu_item-box">
<div class="menu_icon">
- <img class="icon" :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'setting' ? settingIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'tenant' ? tenantIcon : prefixIcon)" alt="">
+ <img class="icon" :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'tenant' ? tenantIcon : prefixIcon)" alt="">
</div>
- <span class="menu_title">{{ item.title }}</span>
+ <span class="menu_title">{{ item.path === 'knowledge-bases' && kbMenuItem ? kbMenuItem.title : item.title }}</span>
</div>
</div>
</div>
@@ -73,16 +96,16 @@
</div>
</template>
-<script setup>
+<script setup lang="ts">
import { storeToRefs } from 'pinia';
-import { onMounted, watch, computed, ref, reactive } from 'vue';
+import { onMounted, watch, computed, ref, reactive, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getSessionsList, delSession } from "@/api/chat/index";
+import { getKnowledgeBaseById, listKnowledgeBases, uploadKnowledgeFile } from '@/api/knowledge-base';
+import { kbFileTypeVerification } from '@/utils/index';
import { useMenuStore } from '@/stores/menu';
import { useAuthStore } from '@/stores/auth';
-import useKnowledgeBase from '@/hooks/useKnowledgeBase';
import { MessagePlugin } from "tdesign-vue-next";
-let { requestMethod } = useKnowledgeBase()
let uploadInput = ref();
const usemenuStore = useMenuStore();
const authStore = useAuthStore();
@@ -97,52 +120,203 @@ const submenuscrollContainer = ref(null);
// 计算总页数
const totalPages = computed(() => Math.ceil(total.value / page_size.value));
const hasMore = computed(() => currentPage.value < totalPages.value);
+type MenuItem = { title: string; icon: string; path: string; childrenPath?: string; children?: any[] };
const { menuArr } = storeToRefs(usemenuStore);
-let activeSubmenu = ref(-1);
+let activeSubmenu = ref<number>(-1);
+
+// 是否处于知识库详情页
+const isInKnowledgeBase = computed<boolean>(() => {
+ return route.name === 'knowledgeBaseDetail' || route.name === 'kbCreatChat' || route.name === 'chat' || route.name === 'knowledgeBaseSettings';
+});
+
+// 统一的菜单项激活状态判断
+const isMenuItemActive = (itemPath: string): boolean => {
+ const currentRoute = route.name;
+
+ switch (itemPath) {
+ case 'knowledge-bases':
+ return currentRoute === 'knowledgeBaseList' ||
+ currentRoute === 'knowledgeBaseDetail' ||
+ currentRoute === 'knowledgeBaseSettings';
+ case 'creatChat':
+ return currentRoute === 'kbCreatChat';
+ case 'tenant':
+ return currentRoute === 'tenant';
+ default:
+ return itemPath === currentpath.value;
+ }
+};
+
+// 统一的图标激活状态判断
+const getIconActiveState = (itemPath: string) => {
+ const currentRoute = route.name;
+
+ return {
+ isKbActive: itemPath === 'knowledge-bases' && (
+ currentRoute === 'knowledgeBaseList' ||
+ currentRoute === 'knowledgeBaseDetail' ||
+ currentRoute === 'knowledgeBaseSettings'
+ ),
+ isCreatChatActive: itemPath === 'creatChat' && currentRoute === 'kbCreatChat',
+ isTenantActive: itemPath === 'tenant' && currentRoute === 'tenant',
+ isChatActive: itemPath === 'chat' && currentRoute === 'chat'
+ };
+};
// 分离上下两部分菜单
-const topMenuItems = computed(() => {
- return menuArr.value.filter(item =>
- item.path === 'knowledgeBase' || item.path === 'creatChat'
+const topMenuItems = computed<MenuItem[]>(() => {
+ return (menuArr.value as unknown as MenuItem[]).filter((item: MenuItem) =>
+ item.path === 'knowledge-bases' || (isInKnowledgeBase.value && item.path === 'creatChat')
);
});
-const bottomMenuItems = computed(() => {
- return menuArr.value.filter(item =>
- item.path !== 'knowledgeBase' && item.path !== 'creatChat'
- );
+const bottomMenuItems = computed<MenuItem[]>(() => {
+ return (menuArr.value as unknown as MenuItem[]).filter((item: MenuItem) => {
+ if (item.path === 'knowledge-bases' || item.path === 'creatChat') {
+ return false;
+ }
+ return true;
+ });
});
+
+// 当前知识库名称和列表
+const currentKbName = ref<string>('')
+const allKnowledgeBases = ref<Array<{ id: string; name: string; embedding_model_id?: string; summary_model_id?: string }>>([])
+const showKbDropdown = ref<boolean>(false)
+
+// 过滤已初始化的知识库
+const initializedKnowledgeBases = computed(() => {
+ return allKnowledgeBases.value.filter(kb =>
+ kb.embedding_model_id && kb.embedding_model_id !== '' &&
+ kb.summary_model_id && kb.summary_model_id !== ''
+ )
+})
+
+// 动态更新知识库菜单项标题
+const kbMenuItem = computed(() => {
+ const kbItem = topMenuItems.value.find(item => item.path === 'knowledge-bases')
+ if (kbItem && isInKnowledgeBase.value && currentKbName.value) {
+ return { ...kbItem, title: currentKbName.value }
+ }
+ return kbItem
+})
+
const loading = ref(false)
-const uploadFile = () => {
+const uploadFile = async () => {
+ // 获取当前知识库ID
+ const currentKbId = await getCurrentKbId();
+
+ // 检查当前知识库的初始化状态
+ if (currentKbId) {
+ try {
+ const kbResponse = await getKnowledgeBaseById(currentKbId);
+ const kb = kbResponse.data;
+
+ // 检查知识库是否已初始化(有 EmbeddingModelID 和 SummaryModelID)
+ if (!kb.embedding_model_id || kb.embedding_model_id === '' ||
+ !kb.summary_model_id || kb.summary_model_id === '') {
+ MessagePlugin.warning("该知识库尚未完成初始化配置,请先前往设置页面配置模型信息后再上传文件");
+ return;
+ }
+ } catch (error) {
+ console.error('获取知识库信息失败:', error);
+ MessagePlugin.error("获取知识库信息失败,无法上传文件");
+ return;
+ }
+ }
+
uploadInput.value.click()
}
-const upload = (e) => {
- requestMethod(e.target.files[0], uploadInput)
+const upload = async (e: any) => {
+ const file = e.target.files[0];
+ if (!file) return;
+
+ // 文件类型验证
+ if (kbFileTypeVerification(file)) {
+ return;
+ }
+
+ // 获取当前知识库ID
+ const currentKbId = (route.params as any)?.kbId as string;
+ if (!currentKbId) {
+ MessagePlugin.error("缺少知识库ID");
+ return;
+ }
+
+ try {
+ const result = await uploadKnowledgeFile(currentKbId, { file });
+ const responseData = result as any;
+ console.log('上传API返回结果:', responseData);
+
+ // 如果没有抛出异常,就认为上传成功,先触发刷新事件
+ console.log('文件上传完成,发送事件通知页面刷新,知识库ID:', currentKbId);
+ window.dispatchEvent(new CustomEvent('knowledgeFileUploaded', {
+ detail: { kbId: currentKbId }
+ }));
+
+ // 然后处理UI消息
+ // 判断上传是否成功 - 检查多种可能的成功标识
+ const isSuccess = responseData.success || responseData.code === 200 || responseData.status === 'success' || (!responseData.error && responseData);
+
+ if (isSuccess) {
+ MessagePlugin.info("上传成功!");
+ } else {
+ // 改进错误信息提取逻辑
+ let errorMessage = "上传失败!";
+ if (responseData.error && responseData.error.message) {
+ errorMessage = responseData.error.message;
+ } else if (responseData.message) {
+ errorMessage = responseData.message;
+ }
+ if (responseData.code === 'duplicate_file' || (responseData.error && responseData.error.code === 'duplicate_file')) {
+ errorMessage = "文件已存在";
+ }
+ MessagePlugin.error(errorMessage);
+ }
+ } catch (err: any) {
+ let errorMessage = "上传失败!";
+ if (err.code === 'duplicate_file') {
+ errorMessage = "文件已存在";
+ } else if (err.error && err.error.message) {
+ errorMessage = err.error.message;
+ } else if (err.message) {
+ errorMessage = err.message;
+ }
+ MessagePlugin.error(errorMessage);
+ } finally {
+ uploadInput.value.value = "";
+ }
}
-const mouseenteBotDownr = (val) => {
+const mouseenteBotDownr = (val: number) => {
activeSubmenu.value = val;
}
const mouseleaveBotDown = () => {
activeSubmenu.value = -1;
}
-const onVisibleChange = (e) => {
+const onVisibleChange = (_e: any) => {
}
-const delCard = (index, item) => {
- delSession(item.id).then(res => {
- if (res && res.success) {
- menuArr.value[1].children.splice(index, 1);
+const delCard = (index: number, item: any) => {
+ delSession(item.id).then((res: any) => {
+ if (res && (res as any).success) {
+ (menuArr.value as any[])[1]?.children?.splice(index, 1);
if (item.id == route.params.chatid) {
- router.push('/platform/creatChat');
+ // 删除当前会话后,跳转到当前知识库的创建聊天页面
+ const kbId = route.params.kbId;
+ if (kbId) {
+ router.push(`/platform/knowledge-bases/${kbId}/creatChat`);
+ } else {
+ router.push('/platform/knowledge-bases');
+ }
}
} else {
MessagePlugin.error("删除失败,请稍后再试!");
}
})
}
-const debounce = (fn, delay) => {
- let timer
- return (...args) => {
+const debounce = (fn: (...args: any[]) => void, delay: number) => {
+ let timer: ReturnType<typeof setTimeout>
+ return (...args: any[]) => {
clearTimeout(timer)
timer = setTimeout(() => fn(...args), delay)
}
@@ -160,59 +334,131 @@ const checkScrollBottom = () => {
}
}
const handleScroll = debounce(checkScrollBottom, 200)
-const getMessageList = () => {
+const getMessageList = async () => {
+ // 仅在知识库内部显示对话列表
+ if (!isInKnowledgeBase.value) {
+ usemenuStore.clearMenuArr();
+ currentKbName.value = '';
+ return;
+ }
+ let kbId = (route.params as any)?.kbId as string
+ // 新的路由格式:/platform/chat/:kbId/:chatid,直接从路由参数获取知识库ID
+ if (!kbId) {
+ usemenuStore.clearMenuArr();
+ currentKbName.value = '';
+ return;
+ }
+
+ // 获取知识库名称和所有知识库列表
+ try {
+ const [kbRes, allKbRes]: any[] = await Promise.all([
+ getKnowledgeBaseById(kbId),
+ listKnowledgeBases()
+ ])
+ if (kbRes?.data?.name) {
+ currentKbName.value = kbRes.data.name
+ }
+ if (allKbRes?.data) {
+ allKnowledgeBases.value = allKbRes.data
+ }
+ } catch {}
+
if (loading.value) return;
loading.value = true;
usemenuStore.clearMenuArr();
- getSessionsList(currentPage.value, page_size.value).then(res => {
+ getSessionsList(currentPage.value, page_size.value).then((res: any) => {
if (res.data && res.data.length) {
- res.data.forEach(item => {
- let obj = { title: item.title ? item.title : "新会话", path: `chat/${item.id}`, id: item.id, isMore: false, isNoTitle: item.title ? false : true }
+ // 过滤出当前知识库的会话
+ const filtered = res.data.filter((s: any) => s.knowledge_base_id === kbId)
+ filtered.forEach((item: any) => {
+ let obj = { title: item.title ? item.title : "新会话", path: `chat/${kbId}/${item.id}`, id: item.id, isMore: false, isNoTitle: item.title ? false : true }
usemenuStore.updatemenuArr(obj)
});
loading.value = false;
}
- if (res.total) {
- total.value = res.total;
+ if ((res as any).total) {
+ total.value = (res as any).total;
}
})
}
-const openMore = (e) => { }
+const openMore = (_e: any) => { }
onMounted(() => {
- currentpath.value = route.name;
- if (route.params.chatid) {
- currentSecondpath.value = `${route.name}/${route.params.chatid}`;
+ const routeName = typeof route.name === 'string' ? route.name : (route.name ? String(route.name) : '')
+ currentpath.value = routeName;
+ if (route.params.chatid && route.params.kbId) {
+ currentSecondpath.value = `chat/${route.params.kbId}/${route.params.chatid}`;
}
getMessageList();
});
watch([() => route.name, () => route.params], (newvalue) => {
- currentpath.value = newvalue[0];
- if (newvalue[1].chatid) {
- currentSecondpath.value = `${newvalue[0]}/${newvalue[1].chatid}`;
+ const nameStr = typeof newvalue[0] === 'string' ? (newvalue[0] as string) : (newvalue[0] ? String(newvalue[0]) : '')
+ currentpath.value = nameStr;
+ if (newvalue[1].chatid && newvalue[1].kbId) {
+ currentSecondpath.value = `chat/${newvalue[1].kbId}/${newvalue[1].chatid}`;
} else {
currentSecondpath.value = "";
}
-
+ // 路由变化时刷新对话列表(仅在知识库内部)
+ getMessageList();
+ // 路由变化时更新图标状态
+ getIcon(nameStr);
});
let fileAddIcon = ref('file-add-green.svg');
let knowledgeIcon = ref('zhishiku-green.svg');
let prefixIcon = ref('prefixIcon.svg');
-let settingIcon = ref('setting.svg');
let logoutIcon = ref('logout.svg');
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' ? 'user-green.svg' : 'user.svg'; // 使用专门的用户图标
- logoutIcon.value = 'logout.svg';
+ const getIcon = (path: string) => {
+ // 根据当前路由状态更新所有图标
+ const kbActiveState = getIconActiveState('knowledge-bases');
+ const creatChatActiveState = getIconActiveState('creatChat');
+ const tenantActiveState = getIconActiveState('tenant');
+
+ // 上传图标:只在知识库相关页面显示绿色
+ fileAddIcon.value = kbActiveState.isKbActive ? 'file-add-green.svg' : 'file-add.svg';
+
+ // 知识库图标:只在知识库页面显示绿色
+ knowledgeIcon.value = kbActiveState.isKbActive ? 'zhishiku-green.svg' : 'zhishiku.svg';
+
+ // 对话图标:只在对话创建页面显示绿色,在知识库页面显示灰色,其他情况显示默认
+ prefixIcon.value = creatChatActiveState.isCreatChatActive ? 'prefixIcon-green.svg' :
+ kbActiveState.isKbActive ? 'prefixIcon-grey.svg' :
+ 'prefixIcon.svg';
+
+ // 租户图标:只在租户页面显示绿色
+ tenantIcon.value = tenantActiveState.isTenantActive ? 'user-green.svg' : 'user.svg';
+
+ // 退出图标:始终显示默认
+ logoutIcon.value = 'logout.svg';
+}
+getIcon(typeof route.name === 'string' ? route.name as string : (route.name ? String(route.name) : ''))
+const handleMenuClick = async (path: string) => {
+ if (path === 'knowledge-bases') {
+ // 知识库菜单项:如果在知识库内部,跳转到当前知识库文件页;否则跳转到知识库列表
+ const kbId = await getCurrentKbId()
+ if (kbId) {
+ router.push(`/platform/knowledge-bases/${kbId}`)
+ } else {
+ router.push('/platform/knowledge-bases')
+ }
+ } else {
+ gotopage(path)
+ }
}
-getIcon(route.name)
-const gotopage = (path) => {
+
+const getCurrentKbId = async (): Promise<string | null> => {
+ let kbId = (route.params as any)?.kbId as string
+ // 新的路由格式:/platform/chat/:kbId/:chatid,直接从路由参数获取
+ if (!kbId && route.name === 'chat' && (route.params as any)?.kbId) {
+ kbId = (route.params as any).kbId
+ }
+ return kbId || null
+}
+
+const gotopage = async (path: string) => {
pathPrefix.value = path;
// 处理退出登录
if (path === 'logout') {
@@ -220,26 +466,84 @@ const gotopage = (path) => {
router.push('/login');
return;
} else {
- router.push(`/platform/${path}`);
+ if (path === 'creatChat') {
+ const kbId = await getCurrentKbId()
+ if (kbId) {
+ router.push(`/platform/knowledge-bases/${kbId}/creatChat`)
+ } else {
+ router.push(`/platform/knowledge-bases`)
+ }
+ } else {
+ router.push(`/platform/${path}`);
+ }
}
getIcon(path)
}
-const getImgSrc = (url) => {
+const getImgSrc = (url: string) => {
return new URL(`/src/assets/img/${url}`, import.meta.url).href;
}
-const mouseenteMenu = (path) => {
- if (pathPrefix.value != 'knowledgeBase' && pathPrefix.value != 'creatChat' && path != 'knowledgeBase') {
+const mouseenteMenu = (path: string) => {
+ if (pathPrefix.value != 'knowledge-bases' && pathPrefix.value != 'creatChat' && path != 'knowledge-bases') {
prefixIcon.value = 'prefixIcon-grey.svg';
}
}
-const mouseleaveMenu = (path) => {
- if (pathPrefix.value != 'knowledgeBase' && pathPrefix.value != 'creatChat' && path != 'knowledgeBase') {
- getIcon(route.name)
+const mouseleaveMenu = (path: string) => {
+ if (pathPrefix.value != 'knowledge-bases' && pathPrefix.value != 'creatChat' && path != 'knowledge-bases') {
+ const nameStr = typeof route.name === 'string' ? route.name as string : (route.name ? String(route.name) : '')
+ getIcon(nameStr)
+ }
+}
+
+// 知识库下拉相关方法
+const toggleKbDropdown = (event?: Event) => {
+ if (event) {
+ event.stopPropagation()
+ }
+ showKbDropdown.value = !showKbDropdown.value
+}
+
+const switchKnowledgeBase = (kbId: string, event?: Event) => {
+ if (event) {
+ event.stopPropagation()
+ }
+ showKbDropdown.value = false
+ const currentRoute = route.name
+
+ // 路由跳转
+ if (currentRoute === 'knowledgeBaseDetail') {
+ router.push(`/platform/knowledge-bases/${kbId}`)
+ } else if (currentRoute === 'kbCreatChat') {
+ router.push(`/platform/knowledge-bases/${kbId}/creatChat`)
+ } else if (currentRoute === 'knowledgeBaseSettings') {
+ router.push(`/platform/knowledge-bases/${kbId}/settings`)
+ } else {
+ router.push(`/platform/knowledge-bases/${kbId}`)
}
+
+ // 刷新右侧内容 - 通过触发页面重新加载或发送事件
+ nextTick(() => {
+ // 发送全局事件通知页面刷新知识库内容
+ window.dispatchEvent(new CustomEvent('knowledgeBaseChanged', {
+ detail: { kbId }
+ }))
+ })
+}
+
+// 点击外部关闭下拉菜单
+const handleClickOutside = () => {
+ showKbDropdown.value = false
}
+onMounted(() => {
+ document.addEventListener('click', handleClickOutside)
+})
+
+watch(() => route.params.kbId, () => {
+ showKbDropdown.value = false
+})
+
</script>
<style lang="less" scoped>
.del_submenu {
@@ -406,6 +710,10 @@ const mouseleaveMenu = (path) => {
font-style: normal;
font-weight: 600;
line-height: 22px;
+ overflow: hidden;
+ white-space: nowrap;
+ max-width: 120px;
+ flex: 1;
}
.submenu {
@@ -491,6 +799,92 @@ const mouseleaveMenu = (path) => {
}
}
}
+
+/* 知识库下拉菜单样式 */
+.kb-dropdown-icon {
+ margin-left: auto;
+ color: #666;
+ transition: transform 0.3s ease, color 0.2s ease;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 16px;
+ height: 16px;
+
+ &.rotate-180 {
+ transform: rotate(180deg);
+ }
+
+ &:hover {
+ color: #07c05f;
+ }
+
+ &.active {
+ color: #07c05f;
+ }
+
+ &.active:hover {
+ color: #05a04f;
+ }
+
+ svg {
+ width: 12px;
+ height: 12px;
+ transition: inherit;
+ }
+}
+
+.kb-dropdown-menu {
+ position: absolute;
+ top: 100%;
+ left: 0;
+ right: 0;
+ background: #fff;
+ border: 1px solid #e5e7eb;
+ border-radius: 6px;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
+ z-index: 1000;
+ max-height: 200px;
+ overflow-y: auto;
+}
+
+.kb-dropdown-item {
+ padding: 8px 16px;
+ cursor: pointer;
+ transition: background-color 0.2s ease;
+ font-size: 14px;
+ color: #333;
+
+ &:hover {
+ background-color: #f5f5f5;
+ }
+
+ &.active {
+ background-color: #07c05f1a;
+ color: #07c05f;
+ font-weight: 500;
+ }
+
+ &:first-child {
+ border-radius: 6px 6px 0 0;
+ }
+
+ &:last-child {
+ border-radius: 0 0 6px 6px;
+ }
+}
+
+.menu_item-box {
+ display: flex;
+ align-items: center;
+ width: 100%;
+ position: relative;
+}
+
+.menu_box {
+ position: relative;
+}
</style>
<style lang="less">
.upload-popup {
diff --git a/frontend/src/hooks/useKnowledgeBase.ts b/frontend/src/hooks/useKnowledgeBase.ts
index f2b8aafe6..8fc646e9c 100644
--- a/frontend/src/hooks/useKnowledgeBase.ts
+++ b/frontend/src/hooks/useKnowledgeBase.ts
@@ -3,29 +3,32 @@ import { storeToRefs } from "pinia";
import { formatStringDate, kbFileTypeVerification } from "../utils/index";
import { MessagePlugin } from "tdesign-vue-next";
import {
- uploadKnowledgeBase,
- getKnowledgeBase,
+ uploadKnowledgeFile,
+ listKnowledgeFiles,
getKnowledgeDetails,
delKnowledgeDetails,
getKnowledgeDetailsCon,
} from "@/api/knowledge-base/index";
import { knowledgeStore } from "@/stores/knowledge";
+import { useRoute } from 'vue-router';
const usemenuStore = knowledgeStore();
-export default function () {
+export default function (knowledgeBaseId?: string) {
+ const route = useRoute();
const { cardList, total } = storeToRefs(usemenuStore);
let moreIndex = ref(-1);
const details = reactive({
title: "",
time: "",
- md: [],
+ md: [] as any[],
id: "",
total: 0
});
const getKnowled = (query = { page: 1, page_size: 35 }) => {
- getKnowledgeBase(query)
+ if (!knowledgeBaseId) return;
+ listKnowledgeFiles(knowledgeBaseId, query)
.then((result: any) => {
let { data, total: totalResult } = result;
- let cardList_ = data.map((item) => {
+ let cardList_ = data.map((item: any) => {
item["file_name"] = item.file_name.substring(
0,
item.file_name.lastIndexOf(".")
@@ -38,16 +41,16 @@ export default function () {
};
});
if (query.page == 1) {
- cardList.value = cardList_;
+ cardList.value = cardList_ as any[];
} else {
- cardList.value.push(...cardList_);
+ (cardList.value as any[]).push(...cardList_);
}
total.value = totalResult;
})
- .catch((err) => {});
+ .catch((_err) => {});
};
- const delKnowledge = (index: number, item) => {
- cardList.value[index].isMore = false;
+ const delKnowledge = (index: number, item: any) => {
+ (cardList.value as any[])[index].isMore = false;
moreIndex.value = -1;
delKnowledgeDetails(item.id)
.then((result: any) => {
@@ -58,7 +61,7 @@ export default function () {
MessagePlugin.error("知识删除失败!");
}
})
- .catch((err) => {
+ .catch((_err) => {
MessagePlugin.error("知识删除失败!");
});
};
@@ -70,12 +73,30 @@ export default function () {
moreIndex.value = -1;
}
};
- const requestMethod = (file: any, uploadInput) => {
+ const requestMethod = (file: any, uploadInput: any) => {
if (file instanceof File && uploadInput) {
if (kbFileTypeVerification(file)) {
return;
}
- uploadKnowledgeBase({ file })
+ // 每次上传时动态解析当前 kbId(优先:路由 -> URL -> 初始参数)
+ let currentKbId: string | undefined;
+ try {
+ currentKbId = (route.params as any)?.kbId as string;
+ } catch {}
+ if (!currentKbId && typeof window !== 'undefined') {
+ try {
+ const match = window.location.pathname.match(/knowledge-bases\/([^/]+)/);
+ if (match && match[1]) currentKbId = match[1];
+ } catch {}
+ }
+ if (!currentKbId) {
+ currentKbId = knowledgeBaseId;
+ }
+ if (!currentKbId) {
+ MessagePlugin.error("缺少知识库ID");
+ return;
+ }
+ uploadKnowledgeFile(currentKbId, { file })
.then((result: any) => {
if (result.success) {
MessagePlugin.info("上传成功!");
@@ -83,27 +104,20 @@ export default function () {
} else {
// 改进错误信息提取逻辑
let errorMessage = "上传失败!";
-
- // 优先从 error 对象中获取错误信息
if (result.error && result.error.message) {
errorMessage = result.error.message;
} else if (result.message) {
errorMessage = result.message;
}
-
- // 检查错误码,如果是重复文件则显示特定提示
if (result.code === 'duplicate_file' || (result.error && result.error.code === 'duplicate_file')) {
errorMessage = "文件已存在";
}
-
MessagePlugin.error(errorMessage);
}
uploadInput.value.value = "";
})
.catch((err: any) => {
- // 改进 catch 中的错误处理
let errorMessage = "上传失败!";
-
if (err.code === 'duplicate_file') {
errorMessage = "文件已存在";
} else if (err.error && err.error.message) {
@@ -111,7 +125,6 @@ export default function () {
} else if (err.message) {
errorMessage = err.message;
}
-
MessagePlugin.error(errorMessage);
uploadInput.value.value = "";
});
@@ -119,7 +132,7 @@ export default function () {
MessagePlugin.error("file文件类型错误!");
}
};
- const getCardDetails = (item) => {
+ const getCardDetails = (item: any) => {
Object.assign(details, {
title: "",
time: "",
@@ -137,23 +150,23 @@ export default function () {
});
}
})
- .catch((err) => {});
+ .catch((_err) => {});
getfDetails(item.id, 1);
};
- const getfDetails = (id, page) => {
+ const getfDetails = (id: string, page: number) => {
getKnowledgeDetailsCon(id, page)
.then((result: any) => {
if (result.success && result.data) {
let { data, total: totalResult } = result;
if (page == 1) {
- details.md = data;
+ (details.md as any[]) = data;
} else {
- details.md.push(...data);
+ (details.md as any[]).push(...data);
}
details.total = totalResult;
}
})
- .catch((err) => {});
+ .catch((_err) => {});
};
return {
cardList,
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index f1fee0765..adb0f9904 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -1,5 +1,5 @@
import { createRouter, createWebHistory } from 'vue-router'
-import { checkInitializationStatus } from '@/api/initialization'
+import { listKnowledgeBases } from '@/api/knowledge-base'
import { useAuthStore } from '@/stores/auth'
import { validateToken } from '@/api/auth'
@@ -8,7 +8,7 @@ const router = createRouter({
routes: [
{
path: "/",
- redirect: "/platform/knowledgeBase",
+ redirect: "/platform/knowledge-bases",
},
{
path: "/login",
@@ -16,12 +16,6 @@ const router = createRouter({
component: () => import("../views/auth/Login.vue"),
meta: { requiresAuth: false, requiresInit: false }
},
- {
- path: "/initialization",
- name: "initialization",
- component: () => import("../views/initialization/InitializationConfig.vue"),
- meta: { requiresInit: false } // 初始化页面不需要检查初始化状态
- },
{
path: "/knowledgeBase",
name: "home",
@@ -42,28 +36,35 @@ const router = createRouter({
meta: { requiresInit: true, requiresAuth: true }
},
{
- path: "knowledgeBase",
- name: "knowledgeBase",
+ path: "knowledge-bases",
+ name: "knowledgeBaseList",
+ component: () => import("../views/knowledge/KnowledgeBaseList.vue"),
+ meta: { requiresInit: true, requiresAuth: true }
+ },
+ {
+ path: "knowledge-bases/:kbId",
+ name: "knowledgeBaseDetail",
component: () => import("../views/knowledge/KnowledgeBase.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
- path: "creatChat",
- name: "creatChat",
+ path: "knowledge-bases/:kbId/creatChat",
+ name: "kbCreatChat",
component: () => import("../views/creatChat/creatChat.vue"),
meta: { requiresInit: true, requiresAuth: true }
},
{
- path: "chat/:chatid",
- name: "chat",
- component: () => import("../views/chat/index.vue"),
+ path: "knowledge-bases/:kbId/settings",
+ name: "knowledgeBaseSettings",
+ component: () => import("../views/initialization/InitializationContent.vue"),
+ props: { isKbSettings: true },
meta: { requiresInit: true, requiresAuth: true }
},
{
- path: "settings",
- name: "settings",
- component: () => import("../views/settings/SystemSettings.vue"),
- meta: { requiresInit: true }
+ path: "chat/:kbId/:chatid",
+ name: "chat",
+ component: () => import("../views/chat/index.vue"),
+ meta: { requiresInit: true, requiresAuth: true }
},
],
},
@@ -110,33 +111,7 @@ router.beforeEach(async (to, from, next) => {
// }
}
- // 检查系统初始化状态
- if (to.meta.requiresInit !== false) {
- try {
- const { initialized } = await checkInitializationStatus()
-
- if (initialized) {
- // 系统已初始化,记录到本地存储并正常跳转
- localStorage.setItem('system_initialized', 'true')
- next()
- } else {
- // 系统未初始化,跳转到初始化页面
- next('/initialization')
- }
- } catch (error) {
- console.error('检查初始化状态失败:', error)
- // 如果是401,跳转登录,不再误导去初始化
- const status = (error as any)?.status
- if (status === 401) {
- next('/login')
- return
- }
- // 其他错误默认认为需要初始化
- next('/initialization')
- }
- } else {
- next()
- }
+ next()
});
export default router
diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts
index 221864a50..ab8a03e04 100644
--- a/frontend/src/stores/auth.ts
+++ b/frontend/src/stores/auth.ts
@@ -1,5 +1,4 @@
import { defineStore } from 'pinia'
-import { resetTestDataLoaded } from '@/api/test-data'
import { ref, computed } from 'vue'
import type { UserInfo, TenantInfo, KnowledgeBaseInfo } from '@/api/auth'
@@ -85,10 +84,6 @@ export const useAuthStore = defineStore('auth', () => {
localStorage.removeItem('weknora_knowledge_bases')
localStorage.removeItem('weknora_current_kb')
- // 重置测试数据加载标志,确保重新登录后会重新获取KB列表
- try {
- resetTestDataLoaded()
- } catch {}
}
const initFromStorage = () => {
diff --git a/frontend/src/stores/knowledge.ts b/frontend/src/stores/knowledge.ts
index 98a7ed25e..29d3a401b 100644
--- a/frontend/src/stores/knowledge.ts
+++ b/frontend/src/stores/knowledge.ts
@@ -4,8 +4,8 @@ import { defineStore } from "pinia";
export const knowledgeStore = defineStore("knowledge", {
state: () => ({
- cardList: ref([]),
- total: ref(0),
+ cardList: ref<any[]>([]),
+ total: ref<number>(0),
}),
actions: {},
});
diff --git a/frontend/src/stores/menu.ts b/frontend/src/stores/menu.ts
index 0b9b93e78..90ebb5bf2 100644
--- a/frontend/src/stores/menu.ts
+++ b/frontend/src/stores/menu.ts
@@ -5,7 +5,7 @@ import { defineStore } from 'pinia';
export const useMenuStore = defineStore('menuStore', {
state: () => ({
menuArr: reactive([
- { title: '知识库', icon: 'zhishiku', path: 'knowledgeBase' },
+ { title: '知识库', icon: 'zhishiku', path: 'knowledge-bases' },
{
title: '对话',
icon: 'prefixIcon',
@@ -13,8 +13,7 @@ export const useMenuStore = defineStore('menuStore', {
childrenPath: 'chat',
children: reactive<object[]>([]),
},
- { title: '账户信息', icon: 'tenant', path: 'tenant' },
- { title: '系统设置', icon: 'setting', path: 'settings' },
+ { title: '系统信息', icon: 'tenant', path: 'tenant' },
{ title: '退出登录', icon: 'logout', path: 'logout' }
]),
isFirstSession: false,
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index 65e8989ec..04f8c71cf 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -10,19 +10,19 @@ export function generateRandomString(length: number) {
return result;
}
-export function formatStringDate(date) {
+export function formatStringDate(date: any) {
let data = new Date(date);
let year = data.getFullYear();
- let month = data.getMonth() + 1;
- let day = data.getDate();
- let hour = data.getHours();
- let minute = data.getMinutes();
- let second = data.getSeconds();
+ let month = String(data.getMonth() + 1).padStart(2, '0');
+ let day = String(data.getDate()).padStart(2, '0');
+ let hour = String(data.getHours()).padStart(2, '0');
+ let minute = String(data.getMinutes()).padStart(2, '0');
+ let second = String(data.getSeconds()).padStart(2, '0');
return (
year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second
);
}
-export function kbFileTypeVerification(file) {
+export function kbFileTypeVerification(file: any) {
let validTypes = ["pdf", "txt", "md", "docx", "doc", "jpg", "jpeg", "png"];
let type = file.name.substring(file.name.lastIndexOf(".") + 1);
if (!validTypes.includes(type)) {
diff --git a/frontend/src/utils/request.ts b/frontend/src/utils/request.ts
index 2e906becd..0d644fba4 100644
--- a/frontend/src/utils/request.ts
+++ b/frontend/src/utils/request.ts
@@ -5,19 +5,6 @@ import { generateRandomString } from "./index";
// API基础URL
const BASE_URL = import.meta.env.VITE_IS_DOCKER ? "" : "http://localhost:8080";
-// 测试数据
-let testData: {
- tenant: {
- id: number;
- name: string;
- api_key: string;
- };
- knowledge_bases: Array<{
- id: string;
- name: string;
- description: string;
- }>;
-} | null = null;
// 创建Axios实例
const instance = axios.create({
@@ -29,15 +16,6 @@ const instance = axios.create({
},
});
-// 设置测试数据
-export function setTestData(data: typeof testData) {
- testData = data;
-}
-
-// 获取测试数据
-export function getTestData() {
- return testData;
-}
instance.interceptors.request.use(
(config) => {
diff --git a/frontend/src/views/auth/Login.vue b/frontend/src/views/auth/Login.vue
index 336c40bd6..0fab857ad 100644
--- a/frontend/src/views/auth/Login.vue
+++ b/frontend/src/views/auth/Login.vue
@@ -145,7 +145,6 @@ import { ref, reactive, computed, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next'
import { login, register } from '@/api/auth'
-import { loadTestData, resetTestDataLoaded } from '@/api/test-data'
import { useAuthStore } from '@/stores/auth'
const router = useRouter()
@@ -272,11 +271,6 @@ const handleLogin = async () => {
MessagePlugin.success('登录成功!')
- // 登录成功后先重置并加载一次测试数据,确保有KB可用
- try {
- resetTestDataLoaded()
- await loadTestData()
- } catch (_) {}
// 等待状态更新完成后再跳转
await nextTick()
diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue
index dc897f716..c770ddc93 100644
--- a/frontend/src/views/chat/index.vue
+++ b/frontend/src/views/chat/index.vue
@@ -38,6 +38,7 @@ const { output, onChunk, isStreaming, isLoading, error, startStream, stopStream
const route = useRoute();
const router = useRouter();
const session_id = ref(route.params.chatid);
+const knowledge_base_id = ref(route.params.kbId);
const created_at = ref('');
const limit = ref(20);
const messagesList = reactive([]);
@@ -57,6 +58,7 @@ watch([() => route.params], (newvalue) => {
}
messagesList.splice(0);
session_id.value = newvalue[0].chatid;
+ knowledge_base_id.value = newvalue[0].kbId;
checkmenuTitle(session_id.value)
let data = {
session_id: session_id.value,
@@ -154,7 +156,14 @@ const sendMsg = async (value) => {
loading.value = true;
messagesList.push({ content: value, role: 'user' });
scrollToBottom();
- await startStream({ session_id: session_id.value, query: value, method: 'POST', url: '/api/v1/knowledge-chat' });
+
+ await startStream({
+ session_id: session_id.value,
+ knowledge_base_id: knowledge_base_id.value,
+ query: value,
+ method: 'POST',
+ url: '/api/v1/knowledge-chat'
+ });
}
// 处理流式数据
diff --git a/frontend/src/views/creatChat/creatChat.vue b/frontend/src/views/creatChat/creatChat.vue
index 268786e4f..10783ba6e 100644
--- a/frontend/src/views/creatChat/creatChat.vue
+++ b/frontend/src/views/creatChat/creatChat.vue
@@ -1,5 +1,5 @@
<template>
- <div v-show="cardList.length" class="dialogue-wrap">
+ <div class="dialogue-wrap">
<div class="dialogue-answers">
<div class="dialogue-title">
<span>基于知识库内容问答</span>
@@ -7,7 +7,17 @@
<InputField @send-msg="sendMsg"></InputField>
</div>
</div>
- <EmptyKnowledge v-show="!cardList.length"></EmptyKnowledge>
+
+
+ <t-dialog v-model:visible="selectVisible" header="选择知识库" :confirmBtn="{ content: '开始对话', theme: 'primary' }" :onConfirm="confirmSelect" :onCancel="() => selectVisible = false">
+ <t-form :data="{ kb: selectedKbId }">
+ <t-form-item label="知识库">
+ <t-select v-model="selectedKbId" :loading="kbLoading" placeholder="请选择知识库">
+ <t-option v-for="kb in kbList" :key="kb.id" :value="kb.id" :label="kb.name" />
+ </t-select>
+ </t-form-item>
+ </t-form>
+ </t-dialog>
</template>
<script setup lang="ts">
import { ref, onUnmounted, watch } from 'vue';
@@ -17,29 +27,52 @@ import { getSessionsList, createSessions, generateSessionsTitle } from "@/api/ch
import { useMenuStore } from '@/stores/menu';
import { useRoute, useRouter } from 'vue-router';
import useKnowledgeBase from '@/hooks/useKnowledgeBase';
-import { getTestData } from '@/utils/request';
+import { listKnowledgeBases } from '@/api/knowledge-base';
let { cardList } = useKnowledgeBase()
const router = useRouter();
+const route = useRoute();
const usemenuStore = useMenuStore();
const sendMsg = (value: string) => {
createNewSession(value);
}
-async function createNewSession(value: string) {
- // 使用测试数据获取知识库ID
- const testData = getTestData();
- if (!testData || testData.knowledge_bases.length === 0) {
- console.error("测试数据未初始化或不包含知识库");
- return;
+const selectVisible = ref(false)
+const selectedKbId = ref<string>('')
+const kbList = ref<Array<{ id: string; name: string }>>([])
+const kbLoading = ref(false)
+
+const ensureKbId = async (): Promise<string | null> => {
+ // 1) 优先使用当前路由上下文(如果来自某个知识库详情页)
+ const routeKb = (route.params as any)?.kbId as string
+ if (routeKb) return routeKb
+
+
+ // 3) 弹窗选择知识库(从接口拉取)
+ kbLoading.value = true
+ try {
+ const res: any = await listKnowledgeBases()
+ kbList.value = res?.data || []
+ if (kbList.value.length === 0) return null
+ selectedKbId.value = kbList.value[0].id
+ selectVisible.value = true
+ return null
+ } finally {
+ kbLoading.value = false
}
+}
- // 使用第一个知识库ID
- const knowledgeBaseId = testData.knowledge_bases[0].id;
+async function createNewSession(value: string) {
+ let knowledgeBaseId = await ensureKbId()
+ if (!knowledgeBaseId) {
+ // 等待用户在弹窗中选择
+ pendingValue.value = value
+ return
+ }
- createSessions({ knowledge_base_id: knowledgeBaseId }).then(res => {
+ createSessions({ knowledge_base_id: knowledgeBaseId }).then(async res => {
if (res.data && res.data.id) {
- getTitle(res.data.id, value)
+ await getTitle(res.data.id, value)
} else {
// 错误处理
console.error("创建会话失败");
@@ -49,12 +82,33 @@ async function createNewSession(value: string) {
})
}
-const getTitle = (session_id: string, value: string) => {
- let obj = { title: '新会话', path: `chat/${session_id}`, id: session_id, isMore: false, isNoTitle: true }
+const pendingValue = ref<string>('')
+const confirmSelect = async () => {
+ if (!selectedKbId.value) return
+ const value = pendingValue.value
+ pendingValue.value = ''
+ selectVisible.value = false
+ createSessions({ knowledge_base_id: selectedKbId.value }).then(async res => {
+ if (res.data && res.data.id) {
+ await getTitle(res.data.id, value, selectedKbId.value)
+ } else {
+ console.error('创建会话失败')
+ }
+ }).catch((e:any) => console.error('创建会话出错:', e))
+}
+
+const getTitle = async (session_id: string, value: string, kbId?: string) => {
+ const finalKbId = kbId || await ensureKbId();
+ if (!finalKbId) {
+ console.error('无法获取知识库ID');
+ return;
+ }
+
+ let obj = { title: '新会话', path: `chat/${finalKbId}/${session_id}`, id: session_id, isMore: false, isNoTitle: true }
usemenuStore.updataMenuChildren(obj);
usemenuStore.changeIsFirstSession(true);
usemenuStore.changeFirstQuery(value);
- router.push(`/platform/chat/${session_id}`);
+ router.push(`/platform/chat/${finalKbId}/${session_id}`);
}
</script>
diff --git a/frontend/src/views/initialization/InitializationConfig.vue b/frontend/src/views/initialization/InitializationConfig.vue
deleted file mode 100644
index fa26650bc..000000000
--- a/frontend/src/views/initialization/InitializationConfig.vue
+++ /dev/null
@@ -1,3498 +0,0 @@
-<template>
- <div class="initialization-container">
- <!-- 页面标题区域 -->
- <div class="initialization-header">
- <div class="header-content">
- <h1>WeKnora 系统初始化配置</h1>
- <p>首次使用需要配置模型和服务信息,完成后即可开始使用系统</p>
- </div>
- <div class="header-actions">
- <t-button size="small" variant="outline" theme="danger" @click="handleLogout">
- 退出登录
- </t-button>
- </div>
- </div>
-
- <!-- 主要内容区域 -->
- <div class="init-content">
- <!-- 顶部公共区域:Ollama 服务状态与已安装模型 -->
- <div class="ollama-summary-card" id="section-ollama">
- <div class="summary-header">
- <span class="title"><t-icon name="server" />Ollama 服务状态</span>
- <t-tag :theme="ollamaStatus.available ? 'success' : 'danger'" size="small" class="state">
- {{ ollamaStatus.available ? `正常 (${ollamaStatus.version||'v?'} )` : (ollamaStatus.error || '未运行') }}
- </t-tag>
- <t-tooltip content="刷新状态">
- <t-icon name="refresh" class="refresh-icon" :class="{ spinning: summaryRefreshing }" @click="refreshOllamaSummary" />
- </t-tooltip>
- </div>
- <div class="summary-body">
- <div class="models">
- <span class="label">Ollama 服务地址</span>
- <div class="model-list">
- <t-tag size="small" theme="default" class="model-pill">{{ ollamaStatus.baseUrl || '未配置' }}</t-tag>
- </div>
- </div>
- <div class="models">
- <span class="label">已安装模型</span>
- <div class="model-list">
- <t-tag v-for="m in installedModels" :key="m" size="small" theme="default" class="model-pill">{{ m }}</t-tag>
- <span v-if="installedModels.length===0" class="empty">暂无</span>
- </div>
- </div>
- </div>
- </div>
-
- <!-- 主配置表单 -->
- <t-form ref="form" :data="formData" :rules="rules" @submit.prevent layout="vertical">
- <!-- LLM 大语言模型配置区域 -->
- <div class="config-section" id="section-llm">
- <h3><t-icon name="chat" class="section-icon" />LLM 大语言模型配置</h3>
- <div class="form-row">
- <t-form-item label="模型来源" name="llm.source">
- <t-radio-group v-model="formData.llm.source" @change="onModelSourceChange('llm')">
- <t-radio value="local">Ollama (本地)</t-radio>
- <t-radio value="remote">Remote API (远程)</t-radio>
- </t-radio-group>
- </t-form-item>
- </div>
-
- <div class="form-row">
- <t-form-item label="模型名称" name="llm.modelName">
- <div class="model-input-with-status">
- <t-input v-model="formData.llm.modelName" placeholder="例如: qwen3:0.6b"
- @blur="onModelNameChange('llm')"
- @input="onModelNameInput('llm')"
- @keyup.enter="onModelNameChange('llm')" />
- <div class="model-status-icon">
- <t-icon
- v-if="formData.llm.source === 'local' && formData.llm.modelName && modelStatus.llm.checked"
- :name="modelStatus.llm.available ? 'check-circle-filled' : 'close-circle-filled'"
- :class="['status-icon', modelStatus.llm.available ? 'installed' : 'not-installed']"
- :title="modelStatus.llm.available ? '已安装' : '未安装'"
- />
- <t-icon
- v-else-if="formData.llm.source === 'local' && formData.llm.modelName && !modelStatus.llm.checked"
- name="help-circle"
- class="status-icon unknown"
- title="未检查"
- />
- <t-icon
- v-else-if="formData.llm.source === 'local' && formData.llm.modelName && modelStatus.llm.downloading"
- name="loading"
- class="status-icon downloading spinning"
- title="下载中"
- />
- </div>
- <!-- 下载按钮:未安装时显示 -->
- <div v-if="formData.llm.source === 'local' && formData.llm.modelName && modelStatus.llm.checked && !modelStatus.llm.available && !modelStatus.llm.downloading" class="download-action">
- <t-tooltip content="下载模型">
- <t-button
- size="small"
- theme="primary"
- @click="downloadModel('llm', formData.llm.modelName)"
- class="download-btn"
- :disabled="modelStatus.llm.downloading"
- >
- <t-icon name="download" />
- </t-button>
- </t-tooltip>
- </div>
-
- </div>
- </t-form-item>
-
- <!-- 下载进度:下载中时显示 -->
- <div v-if="formData.llm.source === 'local' && formData.llm.modelName && modelStatus.llm.downloading" class="download-progress">
- <div class="progress-info">
- <t-icon name="loading" class="loading-icon spinning" />
- <span class="progress-text">下载中</span>
- </div>
- <t-progress :percentage="Number(modelStatus.llm.progress.toFixed(1))" :show-info="false" size="small" class="progress-bar" />
- <div class="progress-message">{{ modelStatus.llm.message }}</div>
- </div>
- </div>
-
- <!-- 远程 API 配置区域 -->
- <div v-if="formData.llm.source === 'remote'" class="remote-config">
- <div class="form-row">
- <t-form-item label="Base URL" name="llm.baseUrl">
- <div class="url-input-with-check">
- <t-input v-model="formData.llm.baseUrl" placeholder="例如: https://api.openai.com/v1, 去除末尾/chat/completions路径后的URL的前面部分"
- @blur="onRemoteConfigChange('llm')"
- @input="onRemoteConfigInput('llm')" />
- <div v-if="formData.llm.modelName && formData.llm.baseUrl" class="check-action">
- <t-tooltip v-if="!modelStatus.llm.available && modelStatus.llm.checked" content="重新检查连接">
- <t-icon
- name="refresh"
- class="refresh-icon"
- :class="{ spinning: modelStatus.llm.checking }"
- @click="checkRemoteModelStatus('llm')"
- />
- </t-tooltip>
- <t-icon
- v-else-if="modelStatus.llm.checked"
- :name="modelStatus.llm.available ? 'check-circle-filled' : 'close-circle-filled'"
- :class="['status-icon', modelStatus.llm.available ? 'installed' : 'not-installed']"
- :title="modelStatus.llm.available ? '连接正常' : '连接失败'"
- />
- <t-icon
- v-else
- name="loading"
- class="status-icon checking spinning"
- title="检查连接中"
- />
- </div>
- </div>
- </t-form-item>
- </div>
- <div class="form-row">
- <t-form-item label="API Key (可选)" name="llm.apiKey">
- <t-input v-model="formData.llm.apiKey" type="password" placeholder="请输入API Key (可选)"
- @blur="onRemoteConfigChange('llm')"
- @input="onRemoteConfigInput('llm')" />
- </t-form-item>
- </div>
-
- <!-- 错误信息显示 -->
- <div v-if="modelStatus.llm.checked && !modelStatus.llm.available && modelStatus.llm.message" class="error-message">
- <t-icon name="error-circle" />
- <span>{{ modelStatus.llm.message }}</span>
- </div>
-
-
- </div>
- </div>
-
- <!-- Embedding 嵌入模型配置区域 -->
- <div class="config-section" id="section-embedding">
- <h3><t-icon name="layers" class="section-icon" />Embedding 嵌入模型配置</h3>
-
- <!-- 已有文件时的禁用提示 -->
- <div v-if="hasFiles" class="embedding-warning">
- <t-alert theme="warning" message="知识库中已有文件,无法修改Embedding模型配置" />
- </div>
-
- <div class="form-row">
- <t-form-item label="模型来源" name="embedding.source">
- <t-radio-group v-model="formData.embedding.source" @change="onModelSourceChange('embedding')" :disabled="hasFiles">
- <t-radio value="local">Ollama (本地)</t-radio>
- <t-radio value="remote">Remote API (远程)</t-radio>
- </t-radio-group>
- </t-form-item>
- </div>
-
- <div class="form-row">
- <t-form-item label="模型名称" name="embedding.modelName">
- <div class="model-input-with-status">
- <t-input v-model="formData.embedding.modelName" placeholder="例如: nomic-embed-text:latest"
- @blur="onModelNameChange('embedding')"
- @input="onModelNameInput('embedding')"
- @keyup.enter="onModelNameChange('embedding')"
- :disabled="hasFiles" />
- <div class="model-status-icon">
- <t-icon
- v-if="formData.embedding.source === 'local' && formData.embedding.modelName && modelStatus.embedding.checked"
- :name="modelStatus.embedding.available ? 'check-circle-filled' : 'close-circle-filled'"
- :class="['status-icon', modelStatus.embedding.available ? 'installed' : 'not-installed']"
- :title="modelStatus.embedding.available ? '已安装' : '未安装'"
- />
- <t-icon
- v-else-if="formData.embedding.source === 'local' && formData.embedding.modelName && !modelStatus.embedding.checked"
- name="help-circle"
- class="status-icon unknown"
- title="未检查"
- />
- <t-icon
- v-else-if="formData.embedding.source === 'local' && formData.embedding.modelName && modelStatus.embedding.downloading"
- name="loading"
- class="status-icon downloading spinning"
- title="下载中"
- />
- </div>
- <!-- 下载按钮:未安装时显示 -->
- <div v-if="formData.embedding.source === 'local' && formData.embedding.modelName && modelStatus.embedding.checked && !modelStatus.embedding.available && !modelStatus.embedding.downloading" class="download-action">
- <t-tooltip content="下载模型">
- <t-button
- size="small"
- theme="primary"
- @click="downloadModel('embedding', formData.embedding.modelName)"
- class="download-btn"
- :disabled="modelStatus.embedding.downloading"
- >
- <t-icon name="download" />
- </t-button>
- </t-tooltip>
- </div>
-
- </div>
- </t-form-item>
-
- </div>
-
- <!-- 向量维度设置 -->
- <div class="form-row">
- <t-form-item label="维度" name="embedding.dimension">
- <div class="dimension-input-with-action">
- <t-input v-model="formData.embedding.dimension"
- :disabled="hasFiles"
- placeholder="请输入向量维度"
- style="width: 100px;"
- @input="onDimensionInput" />
- <t-button
- size="small"
- variant="outline"
- class="detect-dim-btn"
- :loading="embeddingDimDetecting"
- :disabled="hasFiles"
- @click="detectEmbeddingDimension"
- >
- 检测维度
- </t-button>
- </div>
- </t-form-item>
-
- <!-- 下载进度:下载中时显示 -->
- <div v-if="formData.embedding.source === 'local' && formData.embedding.modelName && modelStatus.embedding.downloading" class="download-progress">
- <div class="progress-info">
- <t-icon name="loading" class="loading-icon spinning" />
- <span class="progress-text">下载中 {{ modelStatus.embedding.progress.toFixed(1) }}%</span>
- </div>
- <t-progress :percentage="Number(modelStatus.embedding.progress.toFixed(1))" :show-info="false" size="small" class="progress-bar" />
- <div class="progress-message">{{ modelStatus.embedding.message }}</div>
- </div>
- </div>
-
- <!-- 远程 Embedding API 配置 -->
- <div v-if="formData.embedding.source === 'remote'" class="remote-config">
- <div class="form-row">
- <t-form-item label="Base URL" name="embedding.baseUrl">
- <div class="url-input-with-check">
- <t-input v-model="formData.embedding.baseUrl" placeholder="例如: https://api.openai.com/v1, 去除末尾/embeddings路径后的URL的前面部分"
- :disabled="hasFiles" @blur="onRemoteConfigChange('embedding')"
- @input="onRemoteConfigInput('embedding')" />
- <div v-if="formData.embedding.modelName && formData.embedding.baseUrl && !hasFiles" class="check-action">
- <t-tooltip v-if="!modelStatus.embedding.available && modelStatus.embedding.checked" content="重新检查连接">
- <t-icon
- name="refresh"
- class="refresh-icon"
- :class="{ spinning: modelStatus.embedding.checking }"
- @click="checkEmbeddingModelStatus()"
- />
- </t-tooltip>
- <t-icon
- v-else-if="modelStatus.embedding.checked"
- :name="modelStatus.embedding.available ? 'check-circle-filled' : 'close-circle-filled'"
- :class="['status-icon', modelStatus.embedding.available ? 'installed' : 'not-installed']"
- :title="modelStatus.embedding.available ? '连接正常' : '连接失败'"
- />
- <t-icon
- v-else
- name="loading"
- class="input-icon checking spinning"
- title="检查连接中"
- />
- </div>
- </div>
- </t-form-item>
- </div>
- <div class="form-row">
- <t-form-item label="API Key (可选)" name="embedding.apiKey">
- <t-input v-model="formData.embedding.apiKey" type="password" placeholder="请输入API Key (可选)"
- :disabled="hasFiles" @blur="onRemoteConfigChange('embedding')"
- @input="onRemoteConfigInput('embedding')" />
- </t-form-item>
- </div>
-
- <!-- 错误信息显示 -->
- <div v-if="modelStatus.embedding.checked && !modelStatus.embedding.available && modelStatus.embedding.message" class="error-message">
- <t-icon name="error-circle" />
- <span>{{ modelStatus.embedding.message }}</span>
- </div>
-
-
- </div>
- </div>
-
- <!-- Rerank 重排模型配置区域 -->
- <div class="config-section" id="section-rerank">
- <h3><t-icon name="swap" class="section-icon" />Rerank 重排模型配置</h3>
-
- <div class="form-row">
- <t-form-item name="rerank.enabled">
- <div class="switch-container">
- <t-switch v-model="formData.rerank.enabled" @change="onRerankChange" />
- <span class="switch-label">启用Rerank重排模型</span>
- </div>
- </t-form-item>
- </div>
-
- <!-- Rerank 详细配置 -->
- <div v-if="formData.rerank.enabled" class="rerank-config">
- <div class="form-row">
- <t-form-item label="模型名称" name="rerank.modelName">
- <div class="model-input-with-status">
- <t-input v-model="formData.rerank.modelName" placeholder="例如: bge-reranker-v2-m3"
- @blur="onRerankConfigChange"
- @input="onRerankConfigInput" />
- <div class="model-status-icon">
- <t-icon
- v-if="formData.rerank.modelName && modelStatus.rerank.checked"
- :name="modelStatus.rerank.available ? 'check-circle-filled' : 'close-circle-filled'"
- :class="['status-icon', modelStatus.rerank.available ? 'installed' : 'not-installed']"
- :title="modelStatus.rerank.available ? '连接正常' : '连接失败'"
- />
- <t-icon
- v-else-if="formData.rerank.modelName && !modelStatus.rerank.checked"
- name="help-circle"
- class="status-icon unknown"
- title="未检查"
- />
- </div>
- </div>
- </t-form-item>
- </div>
-
- <div class="form-row">
- <t-form-item label="Base URL" name="rerank.baseUrl">
- <div class="url-input-with-check">
- <t-input v-model="formData.rerank.baseUrl" placeholder="例如: http://localhost:11434, 去除末尾/rerank路径后的URL的前面部分"
- @blur="onRerankConfigChange"
- @input="onRerankConfigInput" />
- <div v-if="formData.rerank.modelName && formData.rerank.baseUrl" class="check-action">
- <t-tooltip v-if="!modelStatus.rerank.available && modelStatus.rerank.checked" content="重新检查连接">
- <t-icon
- name="refresh"
- class="refresh-icon"
- :class="{ spinning: modelStatus.rerank.checking }"
- @click="checkRerankModelStatus"
- />
- </t-tooltip>
- <t-icon
- v-else-if="modelStatus.rerank.checked"
- :name="modelStatus.rerank.available ? 'check-circle-filled' : 'close-circle-filled'"
- :class="['status-icon', modelStatus.rerank.available ? 'installed' : 'not-installed']"
- :title="modelStatus.rerank.available ? '连接正常' : '连接失败'"
- />
- <t-icon
- v-else
- name="loading"
- class="input-icon checking spinning"
- title="检查连接中"
- />
- </div>
- </div>
- </t-form-item>
- </div>
-
- <div class="form-row">
- <t-form-item label="API Key" name="rerank.apiKey">
- <t-input v-model="formData.rerank.apiKey" type="password" placeholder="请输入API Key (可选)"
- @blur="onRerankConfigChange"
- @input="onRerankConfigInput" />
- </t-form-item>
- </div>
-
- <!-- 错误信息显示 -->
- <div v-if="modelStatus.rerank.checked && !modelStatus.rerank.available && modelStatus.rerank.message" class="error-message">
- <t-icon name="error-circle" />
- <span>{{ modelStatus.rerank.message }}</span>
- </div>
-
-
- </div>
- </div>
-
- <!-- 多模态配置区域 -->
- <div class="config-section" id="section-multimodal">
- <h3><t-icon name="image" class="section-icon" />多模态配置</h3>
- <div class="form-row">
- <t-form-item name="multimodal.enabled">
- <div class="switch-container">
- <t-switch v-model="formData.multimodal.enabled" @change="onMultimodalChange" />
- <span class="switch-label">启用多模态图片信息提取</span>
- </div>
- </t-form-item>
- </div>
-
- <!-- 多模态详细配置 -->
- <div v-if="formData.multimodal.enabled" class="multimodal-config">
- <!-- VLM 视觉语言模型配置 -->
- <h4>视觉语言模型配置</h4>
- <div class="form-row">
- <t-form-item label="模型名称" name="multimodal.vlm.modelName">
- <div class="model-input-with-status">
- <t-input v-model="formData.multimodal.vlm.modelName" placeholder="例如: qwen2.5vl:3b"
- @blur="onModelNameChange('vlm')"
- @input="onModelNameInput('vlm')"
- @keyup.enter="onModelNameChange('vlm')" />
- <div class="model-status-icon">
- <t-icon
- v-if="formData.multimodal.vlm.interfaceType === 'ollama' && formData.multimodal.vlm.modelName && modelStatus.vlm.checked"
- :name="modelStatus.vlm.available ? 'check-circle-filled' : 'close-circle-filled'"
- :class="['status-icon', modelStatus.vlm.available ? 'installed' : 'not-installed']"
- :title="modelStatus.vlm.available ? '已安装' : '未安装'"
- />
- <t-icon
- v-else-if="formData.multimodal.vlm.interfaceType === 'ollama' && formData.multimodal.vlm.modelName && !modelStatus.vlm.checked"
- name="help-circle"
- class="status-icon unknown"
- title="未检查"
- />
- <t-icon
- v-else-if="formData.multimodal.vlm.interfaceType === 'ollama' && formData.multimodal.vlm.modelName && modelStatus.vlm.downloading"
- name="loading"
- class="status-icon downloading spinning"
- title="下载中"
- />
- </div>
- <!-- 下载按钮:未安装时显示 -->
- <div v-if="formData.multimodal.vlm.interfaceType === 'ollama' && formData.multimodal.vlm.modelName && modelStatus.vlm.checked && !modelStatus.vlm.available && !modelStatus.vlm.downloading" class="download-action">
- <t-tooltip content="下载模型">
- <t-button
- size="small"
- theme="primary"
- @click="downloadModel('vlm', formData.multimodal.vlm.modelName)"
- class="download-btn"
- :disabled="modelStatus.vlm.downloading"
- >
- <t-icon name="download" />
- </t-button>
- </t-tooltip>
- </div>
-
- </div>
- </t-form-item>
-
- <!-- 下载进度:下载中时显示 -->
- <div v-if="formData.multimodal.vlm.interfaceType === 'ollama' && formData.multimodal.vlm.modelName && modelStatus.vlm.downloading" class="download-progress">
- <div class="progress-info">
- <t-icon name="loading" class="loading-icon spinning" />
- <span class="progress-text">下载中 {{ modelStatus.vlm.progress.toFixed(1) }}%</span>
- </div>
- <t-progress :percentage="Number(modelStatus.vlm.progress.toFixed(1))" :show-info="false" size="small" class="progress-bar" />
- <div class="progress-message">{{ modelStatus.vlm.message }}</div>
- </div>
- </div>
- <div class="form-row">
- <t-form-item label="接口类型" name="multimodal.vlm.interfaceType">
- <t-radio-group v-model="formData.multimodal.vlm.interfaceType" @change="onVlmInterfaceTypeChange">
- <t-radio value="ollama">Ollama (本地)</t-radio>
- <t-radio value="openai">OpenAI 兼容接口</t-radio>
- </t-radio-group>
- </t-form-item>
- </div>
- <div class="form-row" v-if="formData.multimodal.vlm.interfaceType === 'openai'">
- <t-form-item label="Base URL" name="multimodal.vlm.baseUrl">
- <t-input v-model="formData.multimodal.vlm.baseUrl" placeholder="例如: http://localhost:11434/v1,去除末尾/chat/completions路径后的URL的前面部分"
- @blur="onVlmBaseUrlChange"
- @input="onVlmBaseUrlInput" />
- </t-form-item>
- </div>
- <div class="form-row" v-if="formData.multimodal.vlm.interfaceType === 'openai'">
- <t-form-item label="API Key" name="multimodal.vlm.apiKey">
- <t-input v-model="formData.multimodal.vlm.apiKey" type="password" placeholder="请输入API Key (可选)"
- @blur="onVlmApiKeyChange" />
- </t-form-item>
- </div>
-
-
-
- <!-- 对象存储服务配置 -->
- <h4>对象存储服务配置</h4>
- <div class="form-row">
- <t-form-item label="存储类型">
- <t-radio-group v-model="formData.storageType" @change="onStorageTypeChange">
- <t-radio value="cos">COS</t-radio>
- <t-radio value="minio">MinIO</t-radio>
- </t-radio-group>
- </t-form-item>
- </div>
-
- <!-- MinIO 配置区域 -->
- <div v-if="formData.storageType === 'minio'">
- <div class="form-row">
- <t-form-item label="Bucket Name" name="multimodal.minio.bucketName">
- <t-input v-model="formData.multimodal.minio.bucketName" placeholder="请输入Bucket名称" />
- </t-form-item>
- </div>
-
- <div class="form-row">
- <t-form-item label="Path Prefix" name="multimodal.minio.pathPrefix">
- <t-input v-model="formData.multimodal.minio.pathPrefix" placeholder="例如: images" />
- </t-form-item>
- </div>
- </div>
-
- <!-- COS 配置区域 -->
- <div class="form-row">
- <t-form-item v-if="formData.storageType === 'cos'" label="Secret ID" name="multimodal.cos.secretId">
- <t-input v-model="formData.multimodal.cos.secretId" placeholder="请输入COS Secret ID"
- @blur="onCosConfigChange" />
- </t-form-item>
- </div>
- <div class="form-row">
- <t-form-item v-if="formData.storageType === 'cos'" label="Secret Key" name="multimodal.cos.secretKey">
- <t-input v-model="formData.multimodal.cos.secretKey" type="password" placeholder="请输入COS Secret Key"
- @blur="onCosConfigChange" />
- </t-form-item>
- </div>
- <div class="form-row">
- <t-form-item v-if="formData.storageType === 'cos'" label="Region" name="multimodal.cos.region">
- <t-input v-model="formData.multimodal.cos.region" placeholder="例如: ap-beijing"
- @blur="onCosConfigChange" />
- </t-form-item>
- </div>
- <div class="form-row">
- <t-form-item v-if="formData.storageType === 'cos'" label="Bucket Name" name="multimodal.cos.bucketName">
- <t-input v-model="formData.multimodal.cos.bucketName" placeholder="请输入Bucket名称"
- @blur="onCosConfigChange" />
- </t-form-item>
- </div>
- <div class="form-row">
- <t-form-item v-if="formData.storageType === 'cos'" label="App ID" name="multimodal.cos.appId">
- <t-input v-model="formData.multimodal.cos.appId" placeholder="请输入App ID"
- @blur="onCosConfigChange" />
- </t-form-item>
- </div>
- <div class="form-row">
- <t-form-item v-if="formData.storageType === 'cos'" label="Path Prefix" name="multimodal.cos.pathPrefix">
- <t-input v-model="formData.multimodal.cos.pathPrefix" placeholder="例如: images"
- @blur="onCosConfigChange" />
- </t-form-item>
- </div>
-
- <!-- 多模态功能测试区域 -->
- <div v-if="canTestMultimodal" class="multimodal-test">
- <h5>功能测试</h5>
- <p class="test-desc">上传图片测试VLM模型的图片描述和文字识别功能</p>
-
- <div class="test-area">
- <!-- 上传区域 -->
- <div class="upload-section">
- <div class="upload-buttons">
- <t-upload
- ref="imageUpload"
- v-model="multimodalTest.uploadedFiles"
- :show-upload-list="false"
- :auto-upload="false"
- :accept="'image/*'"
- :size-limit="10485760"
- @change="onImageChange"
- >
- <t-button theme="default" variant="outline" size="small">
- <t-icon name="upload" />
- 选择图片
- </t-button>
- </t-upload>
- </div>
- </div>
-
- <!-- 图片预览 -->
- <div v-if="multimodalTest.selectedFile" class="image-preview">
- <img :src="multimodalTest.previewUrl" alt="测试图片" />
- <div class="image-meta">
- <span class="file-name">{{ multimodalTest.selectedFile.name }}</span>
- <span class="file-size">{{ formatFileSize(multimodalTest.selectedFile.size) }}</span>
- </div>
- </div>
-
- <div class="test-button-wrapper">
- <t-button
- v-if="multimodalTest.selectedFile"
- theme="primary"
- size="small"
- :loading="multimodalTest.testing"
- @click="startMultimodalTest"
- >
- 开始测试
- </t-button>
- </div>
- <!-- 测试结果 -->
- <div v-if="multimodalTest.result" class="test-result">
- <div v-if="multimodalTest.result.success" class="result-success">
- <h6>测试结果</h6>
-
- <div v-if="multimodalTest.result.caption" class="result-item">
- <label>图片描述:</label>
- <div class="result-text">{{ multimodalTest.result.caption }}</div>
- </div>
-
- <div v-if="multimodalTest.result.ocr" class="result-item">
- <label>文字识别:</label>
- <div class="result-text">{{ multimodalTest.result.ocr }}</div>
- </div>
-
- <div v-if="multimodalTest.result.processing_time" class="result-time">
- 处理时间: {{ multimodalTest.result.processing_time }}ms
- </div>
- </div>
-
- <div v-else class="result-error">
- <h6>测试失败</h6>
- <div class="error-msg">
- <t-icon name="error-circle" />
- {{ multimodalTest.result.message || '多模态处理失败' }}
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- 文档分割配置区域 -->
- <div class="config-section" id="section-docsplit">
- <h3><t-icon name="cut" class="section-icon" />文档分割配置</h3>
-
- <!-- 预设配置选择 -->
- <div class="form-row preset-row">
- <t-form-item label="分割策略">
- <t-radio-group v-model="selectedPreset" @change="onPresetChange" class="preset-radio-group">
- <t-radio value="balanced" class="preset-radio">
- <div class="preset-content">
- <div class="preset-title">均衡模式</div>
- <div class="preset-desc">块大小: 1000 / 重叠: 200</div>
- </div>
- </t-radio>
- <t-radio value="precision" class="preset-radio">
- <div class="preset-content">
- <div class="preset-title">精准模式</div>
- <div class="preset-desc">块大小: 512 / 重叠: 100</div>
- </div>
- </t-radio>
- <t-radio value="context" class="preset-radio">
- <div class="preset-content">
- <div class="preset-title">上下文模式</div>
- <div class="preset-desc">块大小: 2048 / 重叠: 400</div>
- </div>
- </t-radio>
- <t-radio value="custom" class="preset-radio">
- <div class="preset-content">
- <div class="preset-title">自定义</div>
- <div class="preset-desc">手动配置参数</div>
- </div>
- </t-radio>
- </t-radio-group>
- </t-form-item>
- </div>
-
- <!-- 参数配置网格 -->
- <div class="parameters-grid" :class="{ 'disabled-grid': selectedPreset !== 'custom' }">
- <div class="parameter-group">
- <div class="parameter-label">分块大小</div>
- <div class="parameter-control">
- <t-slider
- v-model="formData.documentSplitting.chunkSize"
- :min="100"
- :max="4000"
- :step="1"
- :disabled="selectedPreset !== 'custom'"
- :marks="{ 100: '100', 1000: '1000', 2000: '2000', 4000: '4000' }"
- class="parameter-slider"
- />
- <div class="parameter-value">{{ formData.documentSplitting.chunkSize }} 字符</div>
- </div>
- <div class="parameter-desc">控制每个文档分块的大小,影响检索精度</div>
- </div>
-
- <div class="parameter-group">
- <div class="parameter-label">分块重叠</div>
- <div class="parameter-control">
- <t-slider
- v-model="formData.documentSplitting.chunkOverlap"
- :min="0"
- :max="1000"
- :step="1"
- :disabled="selectedPreset !== 'custom'"
- :marks="{ 0: '0', 200: '200', 500: '500', 1000: '1000' }"
- class="parameter-slider"
- />
- <div class="parameter-value">{{ formData.documentSplitting.chunkOverlap }} 字符</div>
- </div>
- <div class="parameter-desc">分块间重叠的字符数,保持上下文连贯性</div>
- </div>
-
- <div class="parameter-group">
- <div class="parameter-label">分隔符设置</div>
- <div class="parameter-control">
- <t-select
- v-model="formData.documentSplitting.separators"
- multiple
- :disabled="selectedPreset !== 'custom'"
- placeholder="选择或自定义分隔符"
- class="parameter-select"
- clearable
- creatable
- :options="separatorOptions"
- />
- </div>
- </div>
- </div>
-
- </div>
-
- <!-- 提交按钮区域 -->
- <div class="submit-section" id="section-submit">
- <t-button theme="primary" type="button" size="large"
- :loading="submitting" :disabled="!canSubmit || isSubmitDebounced"
- @click="handleSubmit">
- {{ isUpdateMode ? '更新配置信息' : '完成初始化配置' }}
- </t-button>
-
- <!-- 提交状态提示 -->
- <div v-if="!canSubmit && hasOllamaModels" class="submit-tips">
- <t-icon name="info-circle" class="tip-icon" />
- <span>请等待所有Ollama模型下载完成后再进行初始化</span>
- </div>
-
-
- </div>
- </t-form>
- </div> <!-- .init-content -->
- </div>
-</template>
-
-<script setup lang="ts">
-/**
- * 导入必要的 Vue 组合式 API 和外部依赖
- */
-import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue';
-import { useRouter } from 'vue-router';
-import { MessagePlugin } from 'tdesign-vue-next';
-import {
- initializeSystem,
- checkOllamaStatus,
- checkOllamaModels,
- downloadOllamaModel,
- getDownloadProgress,
- getCurrentConfig,
- checkRemoteModel,
- type DownloadTask,
- checkRerankModel,
- testMultimodalFunction,
- listOllamaModels,
- testEmbeddingModel
- } from '@/api/initialization';
-import { useAuthStore } from '@/stores/auth';
-
-const router = useRouter();
-const authStore = useAuthStore();
-type TFormRef = {
- validate: (fields?: string[] | undefined) => Promise<true | any>;
- clearValidate?: (fields?: string | string[]) => void;
-} | null;
-const form = ref<TFormRef>(null);
-const submitting = ref(false);
-const hasFiles = ref(false);
-const isUpdateMode = ref(false); // 是否为更新模式
-
-// 防抖机制:防止按钮快速重复点击
-const submitDebounceTimer = ref<ReturnType<typeof setTimeout> | null>(null);
-const isSubmitDebounced = ref(false);
-
-// Ollama服务状态
-const ollamaStatus = reactive({
- checked: false,
- available: false,
- version: '',
- error: '',
- baseUrl: ''
-});
-// 顶部摘要:已安装模型
-const installedModels = ref<string[]>([]);
-const summaryRefreshing = ref<boolean>(false);
-
-// 下载任务管理
-const downloadTasks = reactive<Record<string, DownloadTask>>({});
-const progressTimers = reactive<Record<string, any>>({});
-
-// 模型状态管理
-const modelStatus = reactive({
- llm: {
- checked: false,
- available: false,
- downloading: false,
- checking: false,
- taskId: '',
- progress: 0,
- message: ''
- },
- embedding: {
- checked: false,
- available: false,
- downloading: false,
- checking: false,
- taskId: '',
- progress: 0,
- message: ''
- },
- vlm: {
- checked: false,
- available: false,
- downloading: false,
- checking: false,
- taskId: '',
- progress: 0,
- message: ''
- },
- rerank: {
- checked: false,
- available: false,
- downloading: false,
- checking: false,
- taskId: '',
- progress: 0,
- message: ''
- }
-});
-
-// 表单数据
-const formData = reactive({
- llm: {
- source: 'local',
- modelName: '',
- baseUrl: '',
- apiKey: ''
- },
- embedding: {
- source: 'local',
- modelName: '',
- baseUrl: '',
- apiKey: '',
- dimension: 0 // 默认嵌入维度值
- },
- rerank: {
- enabled: false,
- modelName: '',
- baseUrl: '',
- apiKey: ''
- },
- multimodal: {
- enabled: false,
- vlm: {
- modelName: '',
- baseUrl: '',
- apiKey: '',
- interfaceType: 'ollama'
- },
- cos: {
- secretId: '',
- secretKey: '',
- region: '',
- bucketName: '',
- appId: '',
- pathPrefix: ''
- },
- minio: {
- bucketName: '',
- useSSL: false,
- pathPrefix: ''
- }
- },
- documentSplitting: {
- chunkSize: 1000,
- chunkOverlap: 200,
- separators: ['\n\n', '\n', '。', '!', '?', ';', ';']
- },
- storageType: 'minio'
-});
-
-// 预设配置选择
-const selectedPreset = ref('balanced');
-
-// 分隔符选项
-const separatorOptions = [
- { label: '段落分隔符 (\\n\\n)', value: '\n\n' },
- { label: '换行符 (\\n)', value: '\n' },
- { label: '句号 (。)', value: '。' },
- { label: '感叹号 (!)', value: '!' },
- { label: '问号 (?)', value: '?' },
- { label: '分号 (;)', value: ';' },
- { label: '中文分号 (;)', value: ';' },
- { label: '逗号 (,)', value: ',' },
- { label: '中文逗号 (,)', value: ',' }
-];
-
-// 输入防抖定时器
-const inputDebounceTimers = reactive<Record<string, any>>({});
-
-// 多模态测试状态
-const multimodalTest = reactive({
- uploadedFiles: [],
- selectedFile: null as File | null,
- previewUrl: '',
- testing: false,
- result: null as any
-});
-
-const imageUpload = ref(null);
-
-// Embedding 维度检测状态
-const embeddingDimDetecting = ref(false);
-
-
-// 退出登录
-const handleLogout = () => {
- authStore.logout();
- router.replace('/login');
-};
-
-
-// 配置回填
-const loadCurrentConfig = async () => {
- try {
- const config = await getCurrentConfig();
-
- // 设置hasFiles状态
- hasFiles.value = config.hasFiles || false;
-
- // 检查是否已有配置(判断是否为更新模式)
- const hasExistingConfig = config.llm?.modelName || config.embedding?.modelName || config.rerank?.modelName;
- isUpdateMode.value = !!hasExistingConfig;
-
- // 回填表单数据
- if (config.llm) {
- Object.assign(formData.llm, config.llm);
- }
- if (config.embedding) {
- Object.assign(formData.embedding, config.embedding);
- }
- if (config.rerank) {
- Object.assign(formData.rerank, config.rerank);
- }
- 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);
- // 如果没有接口类型,设置默认值
- if (!formData.multimodal.vlm.interfaceType) {
- formData.multimodal.vlm.interfaceType = 'ollama';
- }
- }
- if (config.multimodal.storageType === 'cos' && config.multimodal.cos) {
- Object.assign(formData.multimodal.cos, config.multimodal.cos);
- } 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);
-
- // 根据回填的配置设置预设模式
- const { chunkSize, chunkOverlap } = config.documentSplitting;
- if (chunkSize === 1000 && chunkOverlap === 200) {
- selectedPreset.value = 'balanced';
- } else if (chunkSize === 512 && chunkOverlap === 100) {
- selectedPreset.value = 'precision';
- } else if (chunkSize === 2048 && chunkOverlap === 400) {
- selectedPreset.value = 'context';
- } else {
- selectedPreset.value = 'custom';
- }
- }
-
- // 在配置加载完成后,检查模型状态
- await checkModelsAfterLoading(config);
-
- } catch (error) {
- console.warn('Failed to load current configuration:', error);
- // 如果加载失败,使用默认配置
- isUpdateMode.value = false;
- }
-};
-
-// 加载配置后检查模型状态
-const checkModelsAfterLoading = async (config: any) => {
- // 延迟一点执行,确保DOM已经更新
- setTimeout(async () => {
- // 检查Rerank模型状态
- if (formData.rerank.enabled && formData.rerank.modelName && formData.rerank.baseUrl) {
- await checkRerankModelStatus();
- }
-
- // 如果有多模态配置,也检查VLM模型状态
- if (formData.multimodal.enabled && formData.multimodal.vlm.modelName) {
- if (isVlmOllama.value && ollamaStatus.available) {
- await checkVlmModelStatus();
- }
- }
- }, 300);
-};
-
-// 计算属性:是否为Ollama VLM
-const isVlmOllama = computed(() => {
- return formData.multimodal.vlm.interfaceType === 'ollama';
-});
-
-const hasOllamaModels = computed(() => {
- return (formData.llm.source === 'local' && formData.llm.modelName) ||
- (formData.embedding.source === 'local' && formData.embedding.modelName) ||
- (formData.multimodal.enabled && isVlmOllama.value && formData.multimodal.vlm.modelName);
-});
-
-const canSubmit = computed(() => {
- if (!hasOllamaModels.value) return true;
-
- if (!ollamaStatus.available) return false;
-
- // 检查所有需要的Ollama模型是否都已下载完成
- const checks = [];
-
- if (formData.llm.source === 'local' && formData.llm.modelName) {
- checks.push(modelStatus.llm.available && !modelStatus.llm.downloading);
- }
-
- if (formData.embedding.source === 'local' && formData.embedding.modelName) {
- checks.push(modelStatus.embedding.available && !modelStatus.embedding.downloading);
- }
-
- if (formData.multimodal.enabled && isVlmOllama.value && formData.multimodal.vlm.modelName) {
- checks.push(modelStatus.vlm.available && !modelStatus.vlm.downloading);
- }
-
- return checks.length === 0 || checks.every(check => check);
-});
-
-// 验证Embedding维度
-const validateEmbeddingDimension = (val: any) => {
- val = Number(val);
- if (!val || isNaN(val)) {
- return false;
- }
- // 验证是否为整数且在合理范围内
- return Number.isInteger(val) ;
-};
-
-// 表单验证规则
-const rules = {
- 'llm.modelName': [{ required: true, message: '请输入LLM模型名称', type: 'error' }],
- 'llm.baseUrl': [
- { required: (t: any) => formData.llm.source === 'remote', message: '请输入BaseURL', type: 'error' }
- ],
- 'embedding.modelName': [{ required: true, message: '请输入Embedding模型名称', type: 'error' }],
- 'embedding.baseUrl': [
- { required: (t: any) => formData.embedding.source === 'remote', message: '请输入BaseURL', type: 'error' }
- ],
- 'embedding.dimension': [
- { required: true, message: '请输入Embedding维度', type: 'error' },
- { validator: validateEmbeddingDimension, message: '维度必须为有效整数值,常见取值为768, 1024, 1536, 3584等', type: 'error' }
- ],
- 'rerank.modelName': [
- { required: (t: any) => formData.rerank.enabled, message: '请输入Rerank模型名称', type: 'error' }
- ],
- 'rerank.baseUrl': [
- { required: (t: any) => formData.rerank.enabled, message: '请输入Rerank BaseURL', type: 'error' }
- ],
- 'multimodal.vlm.modelName': [
- { required: (t: any) => formData.multimodal.enabled, message: '请输入VLM模型名称', type: 'error' }
- ],
- 'multimodal.vlm.baseUrl': [
- { required: (t: any) => formData.multimodal.enabled && formData.multimodal.vlm.interfaceType === 'openai', message: '请输入VLM BaseURL', type: 'error' }
- ],
- 'multimodal.cos.secretId': [
- { required: (t: any) => formData.multimodal.enabled && formData.storageType === 'cos', message: '请输入COS Secret ID', type: 'error' }
- ],
- 'multimodal.cos.secretKey': [
- { required: (t: any) => formData.multimodal.enabled && formData.storageType === 'cos', message: '请输入COS Secret Key', type: 'error' }
- ],
- 'multimodal.cos.region': [
- { required: (t: any) => formData.multimodal.enabled && formData.storageType === 'cos', message: '请输入COS Region', type: 'error' }
- ],
- 'multimodal.cos.bucketName': [
- { required: (t: any) => formData.multimodal.enabled && formData.storageType === 'cos', message: '请输入COS Bucket Name', type: 'error' }
- ],
- 'multimodal.cos.appId': [
- { required: (t: any) => formData.multimodal.enabled && formData.storageType === 'cos', message: '请输入COS App ID', type: 'error' }
- ],
- 'multimodal.minio.bucketName': [
- { required: (t: any) => formData.multimodal.enabled && formData.storageType === 'minio', message: '请输入Bucket Name', type: 'error' }
- ]
-};
-
-// 检查Ollama服务状态
-const checkOllama = async () => {
- try {
- const result = await checkOllamaStatus();
- ollamaStatus.checked = true;
- ollamaStatus.available = result.available;
- ollamaStatus.version = result.version || '';
- ollamaStatus.error = result.error || '';
- ollamaStatus.baseUrl = result.baseUrl || '';
-
- if (ollamaStatus.available) {
- // 如果Ollama可用,检查已配置的模型
- await checkAllOllamaModels();
- }
- } catch (error) {
- console.error('检查Ollama状态失败:', error);
- ollamaStatus.checked = true;
- ollamaStatus.available = false;
- ollamaStatus.error = '检查失败';
- }
-};
-
-// 刷新顶部摘要(状态 + 已安装模型)
-const refreshOllamaSummary = async () => {
- if (summaryRefreshing.value) return;
- summaryRefreshing.value = true;
- try {
- await checkOllama();
- const models = await listOllamaModels();
- installedModels.value = models;
- } catch (e) {
- installedModels.value = [];
- } finally {
- // 略延时以保证旋转动画可见
- setTimeout(() => { summaryRefreshing.value = false; }, 300);
- }
-};
-
-// 检查所有Ollama模型状态
-const checkAllOllamaModels = async () => {
- const modelsToCheck = [];
-
- if (formData.llm.source === 'local' && formData.llm.modelName) {
- modelsToCheck.push(formData.llm.modelName);
- }
-
- if (formData.embedding.source === 'local' && formData.embedding.modelName) {
- modelsToCheck.push(formData.embedding.modelName);
- }
-
- if (formData.multimodal.enabled && isVlmOllama.value && formData.multimodal.vlm.modelName) {
- modelsToCheck.push(formData.multimodal.vlm.modelName);
- }
-
- if (modelsToCheck.length === 0) return;
-
- try {
- const result = await checkOllamaModels(modelsToCheck);
-
- // 更新模型状态
- if (formData.llm.source === 'local' && formData.llm.modelName) {
- modelStatus.llm.checked = true;
- modelStatus.llm.available = result.models[formData.llm.modelName] || false;
- }
-
- if (formData.embedding.source === 'local' && formData.embedding.modelName) {
- modelStatus.embedding.checked = true;
- modelStatus.embedding.available = result.models[formData.embedding.modelName] || false;
- }
-
- if (formData.multimodal.enabled && isVlmOllama.value && formData.multimodal.vlm.modelName) {
- modelStatus.vlm.checked = true;
- modelStatus.vlm.available = result.models[formData.multimodal.vlm.modelName] || false;
- }
- } catch (error) {
- console.error('检查模型状态失败:', error);
- }
-};
-
-// 下载模型
-const downloadModel = async (type: 'llm' | 'embedding' | 'vlm', modelName: string) => {
- // 防止重复点击
- if (modelStatus[type].downloading) {
- return;
- }
-
- try {
- // 立即更新状态,防止重复点击
- modelStatus[type].downloading = true;
- modelStatus[type].progress = 0;
- modelStatus[type].message = '正在启动下载...';
-
- // 启动下载任务
- const result = await downloadOllamaModel(modelName);
-
- // 更新任务ID和初始进度
- modelStatus[type].taskId = result.taskId;
- modelStatus[type].progress = result.progress || 0;
- modelStatus[type].message = '下载已开始';
-
- // 如果已经完成,直接更新状态
- if (result.status === 'completed') {
- modelStatus[type].available = true;
- modelStatus[type].downloading = false;
- modelStatus[type].progress = 100;
- modelStatus[type].message = '下载完成';
- MessagePlugin.success(`模型 ${modelName} 下载成功`);
- return;
- }
-
- // 开始轮询进度
- startProgressPolling(type, result.taskId, modelName);
-
- } catch (error) {
- console.error(`启动模型 ${modelName} 下载失败:`, error);
- MessagePlugin.error(`启动模型 ${modelName} 下载失败`);
- modelStatus[type].downloading = false;
- modelStatus[type].message = '下载启动失败';
- }
-};
-
-// 开始轮询下载进度
-const startProgressPolling = (type: 'llm' | 'embedding' | 'vlm', taskId: string, modelName: string) => {
- // 清除之前的定时器
- if (progressTimers[taskId]) {
- clearInterval(progressTimers[taskId]);
- }
-
- // 每2秒查询一次进度
- progressTimers[taskId] = setInterval(async () => {
- try {
- const task = await getDownloadProgress(taskId);
-
- // 更新模型状态
- modelStatus[type].progress = task.progress;
- modelStatus[type].message = task.message;
-
- // 检查是否完成
- if (task.status === 'completed') {
- modelStatus[type].available = true;
- modelStatus[type].downloading = false;
- modelStatus[type].progress = 100;
- modelStatus[type].message = '下载完成';
-
- // 清除定时器
- clearInterval(progressTimers[taskId]);
- delete progressTimers[taskId];
-
- MessagePlugin.success(`模型 ${modelName} 下载成功`);
-
- } else if (task.status === 'failed') {
- modelStatus[type].downloading = false;
- modelStatus[type].message = task.message || '下载失败';
-
- // 清除定时器
- clearInterval(progressTimers[taskId]);
- delete progressTimers[taskId];
-
- MessagePlugin.error(`模型 ${modelName} 下载失败: ${task.message}`);
- }
-
- } catch (error) {
- console.error('查询下载进度失败:', error);
- // 如果查询失败,停止轮询
- clearInterval(progressTimers[taskId]);
- delete progressTimers[taskId];
- modelStatus[type].downloading = false;
- modelStatus[type].message = '查询进度失败';
- }
- }, 2000);
-};
-
-// 停止所有进度轮询
-const stopAllProgressPolling = () => {
- Object.keys(progressTimers).forEach(taskId => {
- clearInterval(progressTimers[taskId]);
- delete progressTimers[taskId];
- });
-};
-
-// 组件卸载时清理定时器
-onUnmounted(() => {
- stopAllProgressPolling();
-
- // 清理输入防抖定时器
- Object.keys(inputDebounceTimers).forEach(key => {
- if (inputDebounceTimers[key]) {
- clearTimeout(inputDebounceTimers[key]);
- delete inputDebounceTimers[key];
- }
- });
-
- // 清理提交防抖定时器
- if (submitDebounceTimer.value) {
- clearTimeout(submitDebounceTimer.value);
- submitDebounceTimer.value = null;
- }
-});
-
-// 事件处理
-const onModelSourceChange = async (type: 'llm' | 'embedding') => {
- // 重置模型状态
- modelStatus[type].checked = false;
- modelStatus[type].available = false;
- modelStatus[type].downloading = false;
-
- // 如果切换到本地,检查Ollama状态
- if (formData[type].source === 'local' && !ollamaStatus.checked) {
- await checkOllama();
- }
-};
-
-const onModelNameChange = async (type: 'llm' | 'embedding' | 'vlm') => {
- if (type === 'vlm') {
- // 总是重置VLM模型状态
- modelStatus.vlm.checked = false;
- modelStatus.vlm.available = false;
- modelStatus.vlm.downloading = false;
-
- if (formData.multimodal.enabled && isVlmOllama.value && formData.multimodal.vlm.modelName) {
- if (ollamaStatus.available) {
- await checkAllOllamaModels();
-
- // 触发表单验证
- setTimeout(() => {
- form.value?.validate(['multimodal.vlm.modelName']);
- }, 100);
- }
- }
- } else {
- // 总是重置模型状态
- modelStatus[type].checked = false;
- modelStatus[type].available = false;
- modelStatus[type].downloading = false;
-
- if (formData[type].source === 'local' && formData[type].modelName) {
- if (ollamaStatus.available) {
- await checkAllOllamaModels();
-
- // 触发表单验证
- setTimeout(() => {
- form.value?.validate([`${type}.modelName`]);
- }, 100);
- }
- }
- }
-};
-
-const onModelNameInput = (type: 'llm' | 'embedding' | 'vlm') => {
- // 清除之前的定时器
- if (inputDebounceTimers[type]) {
- clearTimeout(inputDebounceTimers[type]);
- }
-
- // 重置模型状态
- if (type === 'vlm') {
- modelStatus.vlm.checked = false;
- modelStatus.vlm.available = false;
- modelStatus.vlm.message = '';
- } else {
- modelStatus[type].checked = false;
- modelStatus[type].available = false;
- modelStatus[type].message = '';
- }
-
- // 设置防抖延迟
- inputDebounceTimers[type] = setTimeout(async () => {
- const modelName = type === 'vlm' ? formData.multimodal.vlm.modelName : formData[type].modelName;
-
- // 只有输入了模型名称才进行校验
- if (modelName && modelName.trim()) {
- // 触发表单验证
- form.value?.validate([type === 'vlm' ? 'multimodal.vlm.modelName' : `${type}.modelName`]);
-
- // 如果是远程API,自动检查模型状态
- if (type === 'llm' && formData.llm.source === 'remote' && formData.llm.baseUrl) {
- await checkRemoteModelStatus('llm');
- } else if (type === 'embedding' && formData.embedding.source === 'remote' && formData.embedding.baseUrl) {
- await checkEmbeddingModelStatus();
- } else if (type === 'vlm' && !isVlmOllama.value) {
- // VLM远程API校验可以在这里添加
- }
-
- // 如果是本地模型且Ollama可用,检查模型状态
- if ((type === 'llm' || type === 'embedding') && formData[type].source === 'local' && ollamaStatus.available) {
- await checkAllOllamaModels();
- } else if (type === 'vlm' && isVlmOllama.value && ollamaStatus.available) {
- await checkAllOllamaModels();
- }
- }
- }, 500); // 500ms防抖延迟
-};
-
-const onMultimodalChange = async () => {
- if (formData.multimodal.enabled) {
- // 设置默认的VLM接口类型
- if (!formData.multimodal.vlm.interfaceType) {
- formData.multimodal.vlm.interfaceType = 'ollama';
- }
-
- // 如果是Ollama接口,设置默认的Base URL
- if (formData.multimodal.vlm.interfaceType === 'ollama' && !formData.multimodal.vlm.baseUrl) {
- formData.multimodal.vlm.baseUrl = 'http://localhost:11434/v1';
- }
-
- // 检查VLM模型状态
- if (formData.multimodal.vlm.modelName && isVlmOllama.value) {
- await checkVlmModelStatus();
- }
- }
-};
-
-// 远程配置改变时的处理
-const onRemoteConfigChange = async (type: 'llm' | 'embedding') => {
- // 重置模型状态
- modelStatus[type].checked = false;
- modelStatus[type].available = false;
- modelStatus[type].message = '';
-
- // 如果配置完整,检查模型
- if (formData[type].modelName && formData[type].baseUrl) {
- if (type === 'llm') {
- await checkRemoteModelStatus(type);
- } else if (type === 'embedding') {
- await checkEmbeddingModelStatus();
- }
- }
-};
-
-// 远程配置输入时的处理
-const onRemoteConfigInput = async (type: 'llm' | 'embedding') => {
- // 清除之前的定时器
- const timerKey = `${type}_remote`;
- if (inputDebounceTimers[timerKey]) {
- clearTimeout(inputDebounceTimers[timerKey]);
- }
-
- // 重置模型状态
- modelStatus[type].checked = false;
- modelStatus[type].available = false;
- modelStatus[type].message = '';
-
- // 设置防抖延迟
- inputDebounceTimers[timerKey] = setTimeout(async () => {
- // 只有在有模型名称和Base URL时才进行校验
- if (formData[type].modelName && formData[type].modelName.trim() &&
- formData[type].baseUrl && formData[type].baseUrl.trim()) {
-
- // 触发表单验证
- form.value?.validate([`${type}.modelName`, `${type}.baseUrl`]);
-
- // 自动检查远程API模型状态
- if (type === 'llm') {
- await checkRemoteModelStatus(type);
- } else if (type === 'embedding') {
- await checkEmbeddingModelStatus();
- }
- }
- }, 500); // 500ms防抖延迟
-};
-
-// 检查远程模型
-const checkRemoteModelStatus = async (type: 'llm') => {
- if (!formData[type].modelName || !formData[type].baseUrl) {
- return;
- }
-
- try {
- modelStatus[type].checking = true;
- modelStatus[type].checked = false;
- modelStatus[type].available = false;
- modelStatus[type].message = '';
-
- const result = await checkRemoteModel({
- modelName: formData[type].modelName,
- baseUrl: formData[type].baseUrl,
- apiKey: formData[type].apiKey
- });
-
- modelStatus[type].checked = true;
- modelStatus[type].available = result.available;
- modelStatus[type].message = result.message || '';
-
- // 触发表单验证
- setTimeout(() => {
- form.value?.validate([`${type}.modelName`]);
- }, 100);
-
- } catch (error) {
- console.error(`检查远程${type}模型失败:`, error);
- modelStatus[type].checked = true;
- modelStatus[type].available = false;
- const err = error as any;
- modelStatus[type].message = (err && err.message) || '网络连接失败';
- } finally {
- modelStatus[type].checking = false;
- }
-};
-
-const onPresetChange = () => {
- if (selectedPreset.value === 'balanced') {
- formData.documentSplitting.chunkSize = 1000;
- formData.documentSplitting.chunkOverlap = 200;
- formData.documentSplitting.separators = ['\n\n', '\n', '。', '!', '?', ';', ';'];
- } else if (selectedPreset.value === 'precision') {
- formData.documentSplitting.chunkSize = 512;
- formData.documentSplitting.chunkOverlap = 100;
- formData.documentSplitting.separators = ['\n\n', '\n', '。', '!', '?', ';', ';'];
- } else if (selectedPreset.value === 'context') {
- formData.documentSplitting.chunkSize = 2048;
- formData.documentSplitting.chunkOverlap = 400;
- formData.documentSplitting.separators = ['\n\n', '\n', '。', '!', '?', ';', ';'];
- }
-};
-
-// 处理分隔符输入
-const onSeparatorsChange = (value: string) => {
- formData.documentSplitting.separators = value.split(',').map(s => s.trim()).filter(s => s);
-};
-
-// 最终模型检查
-const performFinalModelCheck = async () => {
- // 收集需要检查的本地模型
- type ModelItem = { name: string; type: string };
- const modelsToCheck: ModelItem[] = [];
-
- if (formData.llm.source === 'local' && formData.llm.modelName) {
- modelsToCheck.push({ name: formData.llm.modelName, type: 'LLM' });
- }
-
- if (formData.embedding.source === 'local' && formData.embedding.modelName) {
- modelsToCheck.push({ name: formData.embedding.modelName, type: 'Embedding' });
- }
-
- if (formData.multimodal.enabled && isVlmOllama.value && formData.multimodal.vlm.modelName) {
- modelsToCheck.push({ name: formData.multimodal.vlm.modelName, type: 'VLM' });
- }
-
- if (modelsToCheck.length === 0) {
- return { success: true };
- }
-
- // 检查Ollama服务状态
- if (!ollamaStatus.available) {
- return {
- success: false,
- message: 'Ollama服务未运行,无法使用本地模型。请启动Ollama服务或改用远程API。'
- };
- }
-
- // 快速检查:如果所有模型状态已知且可用,直接返回成功
- let allModelsAvailable = true;
- const quickCheckResults = [];
-
- if (formData.llm.source === 'local' && formData.llm.modelName) {
- if (modelStatus.llm.checked && modelStatus.llm.available && !modelStatus.llm.downloading) {
- quickCheckResults.push({ name: formData.llm.modelName, type: 'LLM', available: true });
- } else if (modelStatus.llm.downloading) {
- return {
- success: false,
- message: 'LLM模型正在下载中,请等待下载完成后再提交配置。'
- };
- } else {
- allModelsAvailable = false;
- }
- }
-
- if (formData.embedding.source === 'local' && formData.embedding.modelName) {
- if (modelStatus.embedding.checked && modelStatus.embedding.available && !modelStatus.embedding.downloading) {
- quickCheckResults.push({ name: formData.embedding.modelName, type: 'Embedding', available: true });
- } else if (modelStatus.embedding.downloading) {
- return {
- success: false,
- message: 'Embedding模型正在下载中,请等待下载完成后再提交配置。'
- };
- } else {
- allModelsAvailable = false;
- }
- }
-
- if (formData.multimodal.enabled && isVlmOllama.value && formData.multimodal.vlm.modelName) {
- if (modelStatus.vlm.checked && modelStatus.vlm.available && !modelStatus.vlm.downloading) {
- quickCheckResults.push({ name: formData.multimodal.vlm.modelName, type: 'VLM', available: true });
- } else if (modelStatus.vlm.downloading) {
- return {
- success: false,
- message: 'VLM模型正在下载中,请等待下载完成后再提交配置。'
- };
- } else {
- allModelsAvailable = false;
- }
- }
-
- // 如果所有模型状态已知且可用,直接返回成功
- if (allModelsAvailable && quickCheckResults.length === modelsToCheck.length) {
- return { success: true };
- }
-
- // 需要重新检查的模型
- try {
- const modelNames = modelsToCheck.map(m => m.name);
- const result = await checkOllamaModels(modelNames);
-
- // 检查是否有未安装的模型
- const unavailableModels: ModelItem[] = [];
- modelsToCheck.forEach((model: ModelItem) => {
- if (!result.models[model.name]) {
- unavailableModels.push(model);
- }
- });
-
- if (unavailableModels.length > 0) {
- const modelList = unavailableModels.map(m => `${m.type}模型 "${m.name}"`).join('、');
- return {
- success: false,
- message: `以下模型未安装:${modelList}。请先下载这些模型或选择其他已安装的模型。`
- };
- }
-
- return { success: true };
-
- } catch (error) {
- console.error('最终模型检查失败:', error);
- return {
- success: false,
- message: '无法验证模型状态,请检查网络连接后重试。'
- };
- }
-};
-
-// 处理按钮提交
-const handleSubmit = async () => {
- // 防止重复提交和防抖
- if (submitting.value || isSubmitDebounced.value) {
- return;
- }
-
- // 设置防抖状态
- isSubmitDebounced.value = true;
- if (submitDebounceTimer.value) {
- clearTimeout(submitDebounceTimer.value);
- }
- submitDebounceTimer.value = setTimeout(() => {
- isSubmitDebounced.value = false;
- }, 500); // 500ms防抖
-
- // 先进行表单验证
- const validateResult = await form.value?.validate();
-
- if (validateResult === true) {
- // 确保embedding.dimension是数字类型
- if (formData.embedding.dimension) {
- formData.embedding.dimension = Number(formData.embedding.dimension);
- }
-
- // 检查多模态配置
- if (formData.multimodal.enabled) {
- // 检查是否进行了图片测试
- if (!multimodalTest.result) {
- MessagePlugin.warning('您启用了多模态配置,请先上传一张图片进行测试');
- return;
- }
-
- // 检查是否至少有OCR或Caption有结果
- if (!multimodalTest.result.success ||
- (!multimodalTest.result.caption && !multimodalTest.result.ocr) ||
- (multimodalTest.result.caption === "无法生成图片描述" && multimodalTest.result.ocr === "图片中未检测到文字内容")) {
- MessagePlugin.warning('多模态测试未能正确识别图片内容,请重新测试或检查配置');
- return;
- }
- }
-
- submitting.value = true;
-
- try {
- // 最终检查:确保所有本地模型都已下载完成
- const finalCheck = await performFinalModelCheck();
- if (!finalCheck.success) {
- MessagePlugin.error(finalCheck.message || '模型检查失败');
- return;
- }
-
- // 调用初始化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 ? '配置更新成功!' : '系统初始化成功!';
- MessagePlugin.success(successMessage);
-
- // 记录初始化状态,强制刷新路由状态
- localStorage.setItem('system_initialized', 'true');
-
- // 立即跳转到知识库页面,减少延迟感
- router.replace('/platform/knowledgeBase');
-
- } catch (error) {
- console.error('初始化失败:', error);
- const errorMessage = isUpdateMode.value ? '配置更新失败,请检查配置并重试' : '初始化失败,请检查配置并重试';
- const err = error as any;
- MessagePlugin.error((err && err.message) || errorMessage);
- } finally {
- // 确保在所有情况下都重置提交状态
- submitting.value = false;
- }
- }
-};
-
-// 监听表单变化
-watch(() => formData.llm.source, () => onModelSourceChange('llm'));
-watch(() => formData.embedding.source, () => onModelSourceChange('embedding'));
-
-// 组件挂载时检查Ollama状态
-onMounted(async () => {
- // 加载当前配置
- await loadCurrentConfig();
-
- // 总是检查Ollama状态,因为这是独立于具体配置的
- await refreshOllamaSummary();
-
- // 检查已配置模型状态
- await checkAllConfiguredModels();
-});
-
-const onRerankChange = () => {
- // Add any additional logic you want to execute when rerank.enabled changes
- console.log('Rerank enabled:', formData.rerank.enabled);
-};
-
-const onRerankConfigChange = async () => {
- // 重置模型状态
- modelStatus.rerank.checked = false;
- modelStatus.rerank.available = false;
- modelStatus.rerank.message = '';
-
- // 如果配置完整,检查模型
- if (formData.rerank.modelName && formData.rerank.baseUrl) {
- await checkRerankModelStatus();
- }
-};
-
-const onRerankConfigInput = async () => {
- // 清除之前的定时器
- const timerKey = 'rerank_remote';
- if (inputDebounceTimers[timerKey]) {
- clearTimeout(inputDebounceTimers[timerKey]);
- }
-
- // 重置模型状态
- modelStatus.rerank.checked = false;
- modelStatus.rerank.available = false;
- modelStatus.rerank.message = '';
-
- // 设置防抖延迟
- inputDebounceTimers[timerKey] = setTimeout(async () => {
- // 只有在有模型名称和Base URL时才进行校验
- if (formData.rerank.modelName && formData.rerank.modelName.trim() &&
- formData.rerank.baseUrl && formData.rerank.baseUrl.trim()) {
-
- // 触发表单验证
- form.value?.validate(['rerank.modelName', 'rerank.baseUrl']);
-
- // 自动检查Rerank模型状态
- await checkRerankModelStatus();
- }
- }, 500); // 500ms防抖延迟
-};
-
-const checkRerankModelStatus = async () => {
- if (!formData.rerank.modelName || !formData.rerank.baseUrl) {
- return;
- }
-
- try {
- modelStatus.rerank.checking = true;
- modelStatus.rerank.checked = false;
- modelStatus.rerank.available = false;
- modelStatus.rerank.message = '';
-
- const result = await checkRerankModel({
- modelName: formData.rerank.modelName,
- baseUrl: formData.rerank.baseUrl,
- apiKey: formData.rerank.apiKey
- });
-
- modelStatus.rerank.checked = true;
- modelStatus.rerank.available = result.available;
- modelStatus.rerank.message = result.message || '';
-
- // 触发表单验证
- setTimeout(() => {
- form.value?.validate(['rerank.modelName']);
- }, 100);
-
- } catch (error) {
- console.error('检查Rerank模型失败:', error);
- modelStatus.rerank.checked = true;
- modelStatus.rerank.available = false;
- const err = error as any;
- modelStatus.rerank.message = (err && err.message) || '网络连接失败';
- } finally {
- modelStatus.rerank.checking = false;
- }
-};
-
-// 多模态测试相关方法
-const getTestUploadData = () => {
- return {
- vlm_model: formData.multimodal.vlm.modelName,
- vlm_base_url: formData.multimodal.vlm.baseUrl,
- vlm_api_key: formData.multimodal.vlm.apiKey || ''
- };
-};
-
-const onImageChange = (files: any) => {
- if (files && files.length > 0) {
- // 检查多模态配置是否完整
- const missingConfigs: string[] = [];
-
- // 根据存储类型检查必填项
- if (formData.storageType === 'cos') {
- if (!formData.multimodal.cos.secretId) missingConfigs.push('COS Secret ID');
- if (!formData.multimodal.cos.secretKey) missingConfigs.push('COS Secret Key');
- if (!formData.multimodal.cos.region) missingConfigs.push('COS Region');
- if (!formData.multimodal.cos.bucketName) missingConfigs.push('COS Bucket Name');
- if (!formData.multimodal.cos.appId) missingConfigs.push('COS App ID');
- } else if (formData.storageType === 'minio') {
- if (!formData.multimodal.minio.bucketName) missingConfigs.push('MinIO Bucket Name');
- }
-
- // 检查VLM配置
- if (!formData.multimodal.vlm.modelName) {
- missingConfigs.push('VLM 模型名称');
- }
-
- // 如果是OpenAI兼容接口,还需要检查Base URL
- if (formData.multimodal.vlm.interfaceType === 'openai' && !formData.multimodal.vlm.baseUrl) {
- missingConfigs.push('VLM Base URL');
- }
-
- if (missingConfigs.length > 0) {
- const missingList = missingConfigs.join('、');
- MessagePlugin.error(`多模态配置不完整,请先完成多模态配置后再上传图片`);
- return;
- }
-
- const file = files[0].raw || files[0];
- multimodalTest.selectedFile = file;
-
- // 创建预览URL
- if (multimodalTest.previewUrl) {
- URL.revokeObjectURL(multimodalTest.previewUrl);
- }
- multimodalTest.previewUrl = URL.createObjectURL(file);
-
- // 清除之前的测试结果
- multimodalTest.result = null;
-
- MessagePlugin.success('图片上传成功,可以开始测试');
- }
-};
-
-const startMultimodalTest = async () => {
- if (!multimodalTest.selectedFile) {
- MessagePlugin.warning('请先选择一张图片');
- return;
- }
-
- multimodalTest.testing = true;
- multimodalTest.result = null;
-
- try {
- // 准备API参数
- const apiParams: {
- image: File;
- vlm_model: string;
- vlm_base_url: string;
- vlm_api_key: string;
- vlm_interface_type: string;
- storage_type?: 'cos' | 'minio';
- cos_secret_id?: string;
- cos_secret_key?: string;
- cos_region?: string;
- cos_bucket_name?: string;
- cos_app_id?: string;
- cos_path_prefix?: string;
- minio_bucket_name?: string;
- minio_use_ssl?: boolean;
- minio_path_prefix?: string;
- chunk_size: number;
- chunk_overlap: number;
- separators: string[];
- } = {
- image: multimodalTest.selectedFile,
- vlm_model: formData.multimodal.vlm.modelName,
- vlm_base_url: '', // 将在下方设置
- vlm_api_key: '', // 将在下方设置
- vlm_interface_type: formData.multimodal.vlm.interfaceType,
- chunk_size: formData.documentSplitting.chunkSize,
- chunk_overlap: formData.documentSplitting.chunkOverlap,
- separators: formData.documentSplitting.separators
- };
-
- // 根据存储类型附带不同的参数
- if (formData.storageType === 'cos') {
- apiParams.storage_type = 'cos';
- apiParams.cos_secret_id = formData.multimodal.cos.secretId;
- apiParams.cos_secret_key = formData.multimodal.cos.secretKey;
- apiParams.cos_region = formData.multimodal.cos.region;
- apiParams.cos_bucket_name = formData.multimodal.cos.bucketName;
- apiParams.cos_app_id = formData.multimodal.cos.appId;
- apiParams.cos_path_prefix = formData.multimodal.cos.pathPrefix || '';
- } else if (formData.storageType === 'minio') {
- apiParams.storage_type = 'minio';
- apiParams.minio_bucket_name = formData.multimodal.minio.bucketName;
- apiParams.minio_use_ssl = formData.multimodal.minio.useSSL;
- apiParams.minio_path_prefix = formData.multimodal.minio.pathPrefix;
- }
-
- // 如果是OpenAI兼容接口,设置baseUrl和apiKey
- if (formData.multimodal.vlm.interfaceType === 'openai') {
- apiParams.vlm_base_url = formData.multimodal.vlm.baseUrl;
- apiParams.vlm_api_key = formData.multimodal.vlm.apiKey || '';
- } else {
- // Ollama接口使用默认的本地URL
- apiParams.vlm_base_url = 'http://localhost:11434/v1';
- apiParams.vlm_api_key = '';
- }
-
- const result = await testMultimodalFunction(apiParams);
-
- multimodalTest.result = result;
-
- if (result.success) {
- MessagePlugin.success('多模态测试成功');
- } else {
- MessagePlugin.error(`多模态测试失败: ${result.message}`);
- }
- } catch (error) {
- console.error('多模态测试失败:', error);
- multimodalTest.result = {
- success: false,
- message: (error as any)?.message || '测试过程中发生错误'
- };
- MessagePlugin.error('多模态测试失败');
- } finally {
- multimodalTest.testing = false;
- }
-};
-
-const onTestSuccess = (response: any) => {
- console.log('Upload success:', response);
-};
-
-const onTestFail = (error: any) => {
- console.error('Upload failed:', error);
- MessagePlugin.error('图片上传失败');
-};
-
-const formatFileSize = (bytes: number): string => {
- if (bytes === 0) return '0 B';
- const k = 1024;
- const sizes = ['B', 'KB', 'MB', 'GB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
-};
-
-const canTestMultimodal = computed(() => {
- const baseUrlValid = formData.multimodal.vlm.interfaceType === 'ollama' ||
- (formData.multimodal.vlm.interfaceType === 'openai' && formData.multimodal.vlm.baseUrl);
-
- const cosReady = formData.storageType == 'cos' &&
- formData.multimodal.cos.secretId &&
- formData.multimodal.cos.secretKey &&
- formData.multimodal.cos.region &&
- formData.multimodal.cos.bucketName &&
- formData.multimodal.cos.appId;
-
- const minioReady = formData.storageType == 'minio' &&
- formData.multimodal.minio.bucketName;
-
- return (cosReady || minioReady) &&
- !!formData.multimodal.vlm.modelName &&
- baseUrlValid;
-});
-
-const onVlmInterfaceTypeChange = () => {
- // 当接口类型改变时,重置相关状态
- if (formData.multimodal.vlm.interfaceType === 'ollama') {
- // 如果是Ollama,设置默认的Base URL
- formData.multimodal.vlm.apiKey = ''; // 清空API Key
-
- // 重置模型状态检查
- modelStatus.vlm.checked = false;
- modelStatus.vlm.available = false;
-
- // 如果有模型名称,检查模型状态
- if (formData.multimodal.vlm.modelName && ollamaStatus.available) {
- checkVlmModelStatus();
- }
- } else {
- formData.multimodal.vlm.baseUrl = '';
- // 重置模型状态检查
- modelStatus.vlm.checked = false;
- modelStatus.vlm.available = false;
- }
-
- console.log('VLM interface type changed:', formData.multimodal.vlm.interfaceType);
-};
-
-const checkVlmModelStatus = async () => {
- if (!formData.multimodal.vlm.modelName || !formData.multimodal.vlm.baseUrl) {
- return;
- }
-
- try {
- modelStatus.vlm.checked = false;
- modelStatus.vlm.available = false;
- modelStatus.vlm.message = '';
-
- const result = await checkRemoteModel({
- modelName: formData.multimodal.vlm.modelName,
- baseUrl: formData.multimodal.vlm.baseUrl,
- apiKey: formData.multimodal.vlm.apiKey
- });
-
- modelStatus.vlm.checked = true;
- modelStatus.vlm.available = result.available;
- modelStatus.vlm.message = result.message || '';
-
- // 触发表单验证
- setTimeout(() => {
- form.value?.validate(['multimodal.vlm.modelName']);
- }, 100);
-
- } catch (error) {
- console.error('检查VLM模型状态失败:', error);
- modelStatus.vlm.checked = true;
- modelStatus.vlm.available = false;
- const err = error as any;
- modelStatus.vlm.message = (err && err.message) || '网络连接失败';
- }
-};
-
-const onVlmBaseUrlChange = async () => {
- // 清除之前的定时器
- if (inputDebounceTimers['vlm_base_url']) {
- clearTimeout(inputDebounceTimers['vlm_base_url']);
- }
-
- // 重置VLM模型状态
- modelStatus.vlm.checked = false;
- modelStatus.vlm.available = false;
- modelStatus.vlm.message = '';
-
- // 如果配置完整,检查模型状态
- if (formData.multimodal.vlm.modelName && formData.multimodal.vlm.baseUrl) {
- if (isVlmOllama.value) {
- // 如果是Ollama接口,检查模型是否已安装
- if (ollamaStatus.available) {
- await checkAllOllamaModels();
- }
- } else {
- // 如果是OpenAI兼容接口,可以在这里添加远程API检查
- console.log('VLM使用OpenAI兼容接口,跳过本地模型检查');
- }
-
- // 触发表单验证
- setTimeout(() => {
- form.value?.validate(['multimodal.vlm.baseUrl']);
- }, 100);
- }
-};
-
-const onVlmBaseUrlInput = () => {
- // 清除之前的定时器
- if (inputDebounceTimers['vlm_base_url']) {
- clearTimeout(inputDebounceTimers['vlm_base_url']);
- }
-
- // 重置VLM模型状态
- modelStatus.vlm.checked = false;
- modelStatus.vlm.available = false;
- modelStatus.vlm.message = '';
-
- // 设置防抖延迟
- inputDebounceTimers['vlm_base_url'] = setTimeout(async () => {
- // 只有在有模型名称和Base URL时才进行校验
- if (formData.multimodal.vlm.modelName && formData.multimodal.vlm.modelName.trim() &&
- formData.multimodal.vlm.baseUrl && formData.multimodal.vlm.baseUrl.trim()) {
-
- // 触发表单验证
- form.value?.validate(['multimodal.vlm.baseUrl']);
-
- // 自动检查VLM模型状态
- await onVlmBaseUrlChange();
- }
- }, 500); // 500ms防抖延迟
-};
-
-const onVlmApiKeyChange = () => {
- // 清除之前的定时器
- if (inputDebounceTimers['vlm_api_key']) {
- clearTimeout(inputDebounceTimers['vlm_api_key']);
- }
-
- // 重置VLM模型状态
- modelStatus.vlm.checked = false;
- modelStatus.vlm.available = false;
- modelStatus.vlm.message = '';
-
- // 设置防抖延迟
- inputDebounceTimers['vlm_api_key'] = setTimeout(async () => {
- // 只有在有模型名称和Base URL时才进行校验
- if (formData.multimodal.vlm.modelName && formData.multimodal.vlm.modelName.trim() &&
- formData.multimodal.vlm.baseUrl && formData.multimodal.vlm.baseUrl.trim()) {
-
- // 触发表单验证
- form.value?.validate(['multimodal.vlm.apiKey']);
-
- // 自动检查VLM模型状态
- await checkVlmModelStatus();
- }
- }, 500); // 500ms防抖延迟
-};
-
-const onCosConfigChange = () => {
- // 触发表单验证,确保COS配置的完整性
- setTimeout(() => {
- if (formData.storageType === 'cos') {
- form.value?.validate([
- 'multimodal.cos.secretId',
- 'multimodal.cos.secretKey',
- 'multimodal.cos.region',
- 'multimodal.cos.bucketName',
- 'multimodal.cos.appId'
- ]);
- }
- }, 100);
-
- console.log('COS config changed:', formData.multimodal.cos);
-};
-
-const onStorageTypeChange = () => {
- // 切换到 MinIO 时,清理 COS 校验状态
- if (formData.storageType === 'minio') {
- form.value?.clearValidate?.([
- 'multimodal.cos.secretId',
- 'multimodal.cos.secretKey',
- 'multimodal.cos.region',
- 'multimodal.cos.bucketName',
- 'multimodal.cos.appId'
- ]);
- } else {
- form.value?.clearValidate?.([
- 'multimodal.minio.bucketName',
- 'multimodal.minio.pathPrefix'
- ]);
- }
-};
-
-// 检查所有已配置模型的状态
-const checkAllConfiguredModels = async () => {
- // 检查LLM模型
- if (formData.llm.source === 'local' && formData.llm.modelName && ollamaStatus.available) {
- await checkAllOllamaModels();
- } else if (formData.llm.source === 'remote' && formData.llm.modelName && formData.llm.baseUrl) {
- await checkRemoteModelStatus('llm');
- }
-
- // 检查Embedding模型(如果没有文件)
- if (!hasFiles.value) {
- if (formData.embedding.source === 'local' && formData.embedding.modelName && ollamaStatus.available) {
- await checkAllOllamaModels();
- } else if (formData.embedding.source === 'remote' && formData.embedding.modelName && formData.embedding.baseUrl) {
- await checkEmbeddingModelStatus();
- }
- }
-
- // 检查Rerank模型
- if (formData.rerank.enabled && formData.rerank.modelName && formData.rerank.baseUrl) {
- await checkRerankModelStatus();
- }
-
- // 检查VLM模型
- if (formData.multimodal.enabled && formData.multimodal.vlm.modelName) {
- if (isVlmOllama.value && ollamaStatus.available) {
- await checkVlmModelStatus();
- } else if (!isVlmOllama.value && formData.multimodal.vlm.baseUrl) {
- // 这里可以添加检查远程VLM的逻辑(如果有)
- }
- }
-};
-
-const onDimensionInput = (event: any) => {
- formData.embedding.dimension = Number(event.target.value);
-};
-
-// 检查Embedding模型状态
-const checkEmbeddingModelStatus = async () => {
- if (!formData.embedding.modelName) {
- return;
- }
-
- try {
- modelStatus.embedding.checking = true;
- modelStatus.embedding.checked = false;
- modelStatus.embedding.available = false;
- modelStatus.embedding.message = '';
-
- const result = await testEmbeddingModel({
- source: formData.embedding.source as 'local' | 'remote',
- modelName: formData.embedding.modelName,
- baseUrl: formData.embedding.source === 'remote' ? formData.embedding.baseUrl : undefined,
- apiKey: formData.embedding.apiKey || undefined,
- dimension: formData.embedding.dimension || undefined,
- });
-
- modelStatus.embedding.checked = true;
- modelStatus.embedding.available = result.available || false;
- modelStatus.embedding.message = result.message || '';
-
- // 如果检测到维度信息,自动更新
- if (result.available && result.dimension && result.dimension > 0) {
- formData.embedding.dimension = result.dimension;
- }
-
- // 触发表单验证
- setTimeout(() => {
- form.value?.validate(['embedding.modelName']);
- }, 100);
-
- } catch (error) {
- console.error('检查Embedding模型失败:', error);
- modelStatus.embedding.checked = true;
- modelStatus.embedding.available = false;
- const err = error as any;
- modelStatus.embedding.message = (err && err.message) || '检查失败';
- } finally {
- modelStatus.embedding.checking = false;
- }
-};
-
-// 检测并自动填写 Embedding 维度
-const detectEmbeddingDimension = async () => {
- if (hasFiles.value) return;
- // 校验必填:模型来源 + 模型名称;若远程还需 BaseURL
- const source = (formData.embedding.source || '').trim();
- const modelName = (formData.embedding.modelName || '').trim();
- const baseUrl = (formData.embedding.baseUrl || '').trim();
-
- if (!source || !modelName || (source === 'remote' && !baseUrl)) {
- // 触发对应字段校验提示
- const fields: string[] = ['embedding.source', 'embedding.modelName'];
- if (source === 'remote') fields.push('embedding.baseUrl');
- try { await form.value?.validate(fields); } catch {}
- MessagePlugin.warning('请先完整填写Embedding配置');
- return;
- }
-
- embeddingDimDetecting.value = true;
- try {
- const res = await testEmbeddingModel({
- source: source as 'local' | 'remote',
- modelName,
- baseUrl: source === 'remote' ? baseUrl : undefined,
- apiKey: formData.embedding.apiKey || undefined,
- dimension: formData.embedding.dimension || undefined,
- });
- const available = !!res.available;
- const message = res.message || '';
- const dim = Number(res.dimension || 0);
- if (available && dim > 0) {
- formData.embedding.dimension = dim;
- MessagePlugin.success(`检测成功,维度已自动填写为 ${dim}`);
- } else {
- MessagePlugin.error(message || '检测失败');
- }
- } catch (e: any) {
- const msg = e?.message || '检测失败,请检查配置';
- MessagePlugin.error(msg);
- } finally {
- embeddingDimDetecting.value = false;
- }
-};
-</script>
-
-<style lang="less" scoped>
-.initialization-container {
- min-height: 100vh;
- background: #f8fafb;
- padding: 0;
-
- .initialization-header {
- background: #fff;
- border-bottom: 1px solid #e8f0fe;
- padding: 24px 32px;
- display: flex;
- justify-content: space-between;
- align-items: center;
-
- .header-content {
- h1 {
- margin: 0 0 8px;
- font-size: 24px;
- font-weight: 600;
- color: #1f2937;
- }
-
- p {
- margin: 0;
- color: #6b7280;
- font-size: 14px;
- }
- }
-
- .header-actions {
- flex-shrink: 0;
- }
- }
-
- .init-content {
- max-width: 1200px;
- margin: 0 auto;
- padding: 24px 32px;
- }
- .config-section {
- background: #fff;
- border: 1px solid #e8f0fe;
- border-radius: 12px;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
- padding: 24px;
- margin-bottom: 24px;
-
- h3 {
- display: flex;
- align-items: center;
- gap: 8px;
- margin: 0 0 20px;
- font-size: 18px;
- font-weight: 600;
- color: #1f2937;
- padding-bottom: 12px;
- border-bottom: 1px solid #f3f4f6;
- }
-
- .section-icon {
- color: #07c05f;
- font-size: 20px;
- }
- }
- .ollama-summary-card {
- background: #fff;
- border: 1px solid #e8f0fe;
- border-radius: 12px;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
- padding: 20px;
- margin-bottom: 24px;
-
- .summary-header {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-bottom: 6px;
-
- .title {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- font-weight: 600;
- color: #1f2937;
- }
- .state{ margin-left: 4px; }
- .refresh-icon{
- margin-left: 4px;
- cursor: pointer;
- color: #6b7280;
- transition: transform .2s ease, color .2s ease;
- }
- .refresh-icon:hover{ color: #0ea5e9; }
- .refresh-icon.spinning{ animation: spin 1s linear infinite; }
- }
-
- .summary-body {
- .models {
- display: flex;
- align-items: flex-start;
- gap: 10px;
- .label { color:#6b7280; font-size: 12px; margin-top: 2px; }
- .model-list { display: flex; gap: 6px; flex-wrap: wrap; }
- .model-pill { border-radius: 10px; }
- .empty { color:#9ca3af; font-size:12px; }
- }
- }
- }
-
- .config-section {
- margin-bottom: 32px;
- border-bottom: 1px solid #eef2f7;
- padding-bottom: 24px;
-
- &:last-of-type {
- border-bottom: none;
- margin-bottom: 20px;
- }
-
- h3 {
- color: #07c05f;
- font-size: 18px;
- font-weight: 600;
- margin-bottom: 16px;
- display: flex;
- align-items: center;
- padding: 10px 16px;
- /* 标题条更清爽的浅色渐变 */
- background: linear-gradient(90deg, #f6f9ff, #f4fff6);
- border-radius: 10px;
- border-left: 4px solid #07c05f;
-
- .section-icon {
- margin-right: 8px;
- color: #07c05f;
- font-size: 20px;
- }
- }
-
- h4 {
- color: #333;
- font-size: 16px;
- font-weight: 500;
- margin: 20px 0 15px 0;
- padding-left: 12px;
- border-left: 3px solid #07c05f;
- }
- }
-
- .remote-config, .multimodal-config, .rerank-config {
- margin-top: 16px;
- padding: 18px 16px;
- background: #f9fcff;
- border-radius: 12px;
- border: 1px solid #edf2f7;
- }
-
- .ollama-status {
- margin-top: 15px;
- padding: 15px;
- background: #f0faf0;
- border-radius: 8px;
- border-left: 4px solid #52c41a;
-
- .status-item {
- display: flex;
- align-items: center;
- margin-bottom: 8px;
- flex-direction: column;
- align-items: flex-start;
-
- &:last-child {
- margin-bottom: 0;
- }
-
- .status-header {
- display: flex;
- align-items: center;
- margin-bottom: 5px;
-
- .status-label {
- font-weight: 500;
- margin-right: 10px;
- min-width: 120px;
- color: #333;
- }
-
- :deep(.t-tag) {
- margin-right: 10px;
- border-radius: 8px;
- font-weight: 500;
- &.t-tag--success {
- background-color: #f6ffed;
- border-color: #b7eb8f;
- color: #2f9a28;
- }
- &.t-tag--danger {
- background-color: #fff2f0;
- border-color: #ffccc7;
- color: #d4380d;
- }
- }
-
- :deep(.t-button) {
- margin-bottom: 5px;
- border-radius: 10px;
- &.t-button--theme-primary {
- background-color: #07c05f;
- border-color: #07c05f;
- &:hover {
- background-color: #00a651;
- border-color: #00a651;
- }
- }
- }
- }
-
- .download-progress {
- margin-top: 8px;
- width: 100%;
- max-width: 400px;
-
-
- .progress-text {
- font-size: 12px;
- color: #666;
- margin-top: 4px;
- display: block;
- }
- }
- }
- }
-
- .remote-status {
- margin-top: 15px;
- padding: 12px 16px;
- transition: all 0.3s ease;
- display: flex;
- align-items: center;
- gap: 12px;
- flex-wrap: wrap;
-
- :deep(.t-tag) {
- display: flex;
- align-items: center;
- gap: 4px;
- padding: 4px 8px;
- border-radius: 8px;
- font-size: 12px;
- font-weight: 500;
- transition: all 0.3s ease;
-
- &.t-tag--success {
- background-color: #f6ffed;
- border-color: #b7eb8f;
- color: #52c41a;
- animation: statusFadeIn 0.5s ease;
- }
-
- &.t-tag--danger {
- background-color: #fff2f0;
- border-color: #ffccc7;
- color: #ff4d4f;
- animation: statusFadeIn 0.5s ease;
- }
-
- &.t-tag--default {
- background-color: #fafafa;
- border-color: #d9d9d9;
- color: #666;
- }
-
- .t-icon {
- font-size: 14px;
-
- &[name="loading"] {
- animation: spin 1s linear infinite;
- }
- }
- }
-
- :deep(.t-button) {
- padding: 4px 8px;
- font-size: 12px;
- height: auto;
- transition: all 0.3s ease;
-
- &.t-button--theme-primary {
- color: #1890ff;
-
- &:hover {
- color: #40a9ff;
- background-color: #eef6ff;
- }
- }
- }
-
- .error-message {
- width: 100%;
- margin-top: 8px;
- padding: 8px 12px;
- background: #fff2f0;
- border-radius: 6px;
- border-left: 3px solid #ff4d4f;
- font-size: 12px;
- color: #ff4d4f;
- display: flex;
- align-items: flex-start;
- gap: 6px;
- line-height: 1.4;
- animation: errorSlideIn 0.4s ease;
-
- .t-icon {
- font-size: 14px;
- color: #ff4d4f;
- margin-top: 1px;
- flex-shrink: 0;
- }
- }
- }
-
- // 动画定义
- @keyframes spin {
- from {
- transform: rotate(0deg);
- }
- to {
- transform: rotate(360deg);
- }
- }
-
- @keyframes statusFadeIn {
- from {
- opacity: 0;
- transform: scale(0.8);
- }
- to {
- opacity: 1;
- transform: scale(1);
- }
- }
-
- @keyframes errorSlideIn {
- from {
- opacity: 0;
- transform: translateY(-10px);
- }
- to {
- opacity: 1;
- transform: translateY(0);
- }
- }
-
- .submit-section {
- text-align: center;
- padding-top: 20px;
-
- :deep(.t-button--theme-primary) {
- background: linear-gradient(135deg, #07c05f, #00a651);
- border: none;
- border-radius: 12px;
- font-weight: 600;
- padding: 12px 32px;
- font-size: 16px;
- transition: all 0.2s ease;
- min-height: 48px;
- min-width: 160px;
-
- &:hover:not(.t-is-disabled) {
- background: linear-gradient(135deg, #00a651, #009645);
- box-shadow: 0 8px 25px rgba(7, 192, 95, 0.3);
- }
-
- &:active:not(.t-is-disabled) {
- transform: translateY(0);
- box-shadow: 0 4px 15px rgba(7, 192, 95, 0.2);
- }
-
- &.t-is-disabled {
- background: #ccc;
- color: #999;
- transform: none;
- box-shadow: none;
- }
-
- &.t-is-loading {
- background: linear-gradient(135deg, #07c05f, #00a651);
- color: white;
- transform: none;
- box-shadow: 0 4px 15px rgba(7, 192, 95, 0.2);
- }
- }
-
- :deep(.t-button--theme-default) {
- border-color: #d9d9d9;
- color: #666;
-
- &:hover {
- border-color: #07c05f;
- color: #07c05f;
- }
- }
-
- .submit-tips {
- margin-top: 15px;
- display: flex;
- align-items: center;
- justify-content: center;
- color: #fa8c16;
- font-size: 14px;
-
- .tip-icon {
- margin-right: 5px;
-
- &.spinning {
- animation: spin 1s linear infinite;
- }
- }
- }
- }
-
- :deep(.t-form-item__label) {
- font-weight: 500;
- color: #333;
- font-size: 14px;
- }
-
- :deep(.t-input), :deep(.t-radio-group), :deep(.t-input-number) {
- width: 100%;
-
- .t-input__inner {
- border-radius: 6px;
- transition: all 0.3s ease;
-
- &:focus {
- border-color: #07c05f;
- box-shadow: 0 0 0 2px rgba(7, 192, 95, 0.2);
- }
- }
- }
-
- /* 统一表单项上下间距 */
- :deep(.t-form .t-form-item) {
- margin-bottom: 16px;
- }
-
- /* 统一输入类控件高度与内边距(Input/Select/InputNumber) */
- :deep(.t-input .t-input__inner),
- :deep(.t-select .t-input__inner),
- :deep(.t-input-number .t-input__inner) {
- height: 40px;
- padding: 8px 12px;
- }
-
- /* 统一按钮基础大小(不影响特制的提交按钮) */
- :deep(.t-button) {
- height: 36px;
- padding: 0 14px;
- }
- :deep(.t-button.t-size-s) {
- height: 28px;
- padding: 0 10px;
- }
-
- :deep(.t-radio-button) {
- .t-radio-button__inner {
- border-color: #d9d9d9;
-
- &:hover {
- border-color: #07c05f;
- color: #07c05f;
- }
- }
-
- &.t-is-checked .t-radio-button__inner {
- background-color: #07c05f;
- border-color: #07c05f;
- color: white;
- }
- }
-
-
- :deep(.t-button) {
- min-width: 120px;
- border-radius: 6px;
- font-weight: 500;
- }
-
- .form-tip {
- font-size: 12px;
- color: #888;
- margin-top: 4px;
- line-height: 1.4;
- }
-
- /* 模型输入框与状态图标布局 */
- .model-input-with-status {
- display: flex;
- gap: 8px;
- }
-
- /* 模型名称输入框样式 */
- .model-input-with-status :deep(.t-input) {
- flex: 1;
- min-width: 300px;
-
- .t-input__inner {
- height: 40px;
- font-size: 14px;
- padding: 8px 12px;
- }
- }
-
- /* 下载按钮样式 - 简化设计 */
- .download-action {
- flex-shrink: 0;
- }
-
- .download-action .download-btn {
- height: 22px;
- width: 22px;
- min-width: 22px;
- padding: 0;
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- background: linear-gradient(135deg, #07c05f, #00a651);
- border: none;
- color: white;
- transition: all 0.2s ease;
- box-shadow: 0 2px 8px rgba(7, 192, 95, 0.2);
-
- &:hover:not(:disabled) {
- background: linear-gradient(135deg, #00a651, #008f47);
- box-shadow: 0 4px 12px rgba(7, 192, 95, 0.3);
- }
-
- &:active:not(:disabled) {
- transform: translateY(0);
- box-shadow: 0 2px 6px rgba(7, 192, 95, 0.2);
- }
-
- &:disabled {
- background: #e5e7eb;
- color: #9ca3af;
- cursor: not-allowed;
- transform: none;
- box-shadow: none;
- }
-
- .t-icon {
- font-size: 14px;
- }
- }
-
- /* 下载进度样式 */
- .download-progress {
- margin-top: 8px;
- margin-bottom: 8px;
- padding: 10px 12px;
- background: linear-gradient(135deg, #f0fdf4, #f8fafc);
- border-radius: 8px;
- border: 1px solid #dcfce7;
- box-shadow: 0 1px 4px rgba(7, 192, 95, 0.08);
- width: 100%;
-
- .progress-info {
- display: flex;
- align-items: center;
- gap: 6px;
- margin-bottom: 6px;
-
- .loading-icon {
- color: #07c05f;
- font-size: 14px;
- animation: spin 1s linear infinite;
- }
-
- .progress-text {
- font-size: 12px;
- color: #166534;
- font-weight: 600;
- }
- }
-
- .progress-bar {
- margin-bottom: 4px;
-
- :deep(.t-progress__bar) {
- background: linear-gradient(90deg, #07c05f, #00a651);
- border-radius: 4px;
- height: 4px;
- box-shadow: 0 1px 2px rgba(7, 192, 95, 0.2);
- }
-
- :deep(.t-progress__track) {
- background-color: #e5e7eb;
- border-radius: 4px;
- height: 4px;
- }
- }
-
- .progress-message {
- font-size: 10px;
- color: #6b7280;
- text-align: center;
- line-height: 1.2;
- font-style: italic;
- }
- }
-
- /* URL输入框与检查按钮布局 */
- .url-input-with-check {
- display: flex;
- align-items: center;
- gap: 8px;
- width: 100%;
- }
-
- /* 维度输入框与“检测维度”按钮同一行布局 */
- .dimension-input-with-action {
- display: flex;
- align-items: center;
- gap: 8px;
- }
- .dimension-input-with-action :deep(.t-input) {
- flex: 0 0 auto;
- }
- .detect-dim-btn {
- flex: 0 0 auto;
- }
-
- .url-input-with-check :deep(.t-input) {
- flex: 1;
- min-width: 0;
- width: 100%;
-
- .t-input__inner {
- height: 40px;
- font-size: 14px;
- padding: 8px 12px;
- width: 100%;
- }
- }
-
- /* 检查按钮和状态图标样式 - 与Ollama状态图标保持一致 */
- .check-action {
- flex-shrink: 0;
- display: flex;
- align-items: center;
- justify-content: center;
- min-width: 22px;
- }
-
- .check-action .status-icon,
- .check-action .input-icon {
- font-size: 18px;
- cursor: help;
- color: #666;
- }
-
- .check-action .status-icon.installed,
- .check-action .input-icon.installed {
- color: #00a870;
- }
-
- .check-action .status-icon.not-installed,
- .check-action .input-icon.not-installed {
- color: #e34d59;
- }
-
- .check-action .status-icon.unknown,
- .check-action .input-icon.unknown {
- color: #d54941;
- }
-
- .check-action .status-icon.checking,
- .check-action .input-icon.checking {
- color: #0052d9;
- }
-
- /* 错误信息样式 */
- .error-message {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-top: 8px;
- padding: 8px 12px;
- background-color: #fff2f0;
- border: 1px solid #ffccc7;
- border-radius: 6px;
- color: #d4380d;
- font-size: 13px;
-
- .t-icon {
- color: #d4380d;
- font-size: 16px;
- flex-shrink: 0;
- }
-
- span {
- line-height: 1.4;
- }
- }
-
- /* 输入框样式优化 */
- :deep(.t-input) {
- border-radius: 8px;
-
- &.t-is-focused {
- border-color: #07c05f;
- box-shadow: 0 0 0 2px rgba(7, 192, 95, 0.1);
- }
-
- .t-input__inner {
- border-radius: 8px;
- transition: all 0.2s ease;
-
- &:focus {
- border-color: #07c05f;
- box-shadow: none;
- outline: none;
- }
-
- &:hover {
- border-color: #07c05f;
- }
- }
- }
-
- :deep(.t-textarea) {
- border-radius: 8px;
-
- &.t-is-focused {
- border-color: #07c05f;
- box-shadow: 0 0 0 2px rgba(7, 192, 95, 0.1);
- }
-
- .t-textarea__inner {
- border-radius: 8px;
- border: 1px solid #dcdcdc;
- transition: all 0.2s ease;
-
- &:focus {
- border-color: #07c05f;
- box-shadow: none;
- outline: none;
- }
-
- &:hover {
- border-color: #07c05f;
- }
- }
- }
-
- .model-status-icon {
- flex-shrink: 0;
- width: 22px;
- display: flex;
- align-items: center;
- justify-content: center;
- }
-
- .model-status-icon .status-icon {
- font-size: 18px;
- cursor: help;
- }
-
- .model-status-icon .status-icon.installed {
- color: #00a870;
- }
-
- .model-status-icon .status-icon.not-installed {
- color: #e34d59;
- }
-
- .model-status-icon .status-icon.unknown {
- color: #d54941;
- }
-
- .model-status-icon .status-icon.downloading {
- color: #0052d9;
- }
-
- /* 紧随输入框的精简状态行 */
- .inline-status-row {
- display: flex;
- align-items: center;
- gap: 10px;
- padding: 6px 8px 0;
- }
-
- .inline-progress {
- display: flex;
- align-items: center;
- gap: 8px;
- min-width: 180px;
- padding: 4px 8px;
- background: #f8f9fa;
- border-radius: 12px;
- border: 1px solid #e9ecef;
-
- :deep(.t-progress) {
- flex: 1;
- min-width: 100px;
-
- .t-progress__track {
- background-color: #e9ecef;
- border-radius: 6px;
- }
- }
-
- .progress-text {
- font-size: 11px;
- color: #6c757d;
- font-weight: 500;
- min-width: 45px;
- text-align: right;
- }
- }
-
- .form-row {
- margin-bottom: 16px;
- }
-
- .embedding-dimension {
- display: flex;
- align-items: center;
- gap: 10px;
-
- .t-input-number {
- width: 160px;
- }
-
- .dimension-help {
- color: #666;
- font-size: 12px;
- }
- }
-
- .switch-container {
- display: flex;
- align-items: center;
- justify-content: flex-start;
- margin-left: 0;
-
- .switch-label {
- margin-left: 10px;
- font-size: 14px;
- color: #333;
- font-weight: 500;
- }
- }
-
- .embedding-warning {
- margin-bottom: 20px;
-
- :deep(.t-alert) {
- background-color: #fffbe6;
- border-color: #ffe58f;
- border-radius: 8px;
-
- .t-alert__message {
- color: #d48806;
- font-weight: 500;
- }
-
- .t-alert__icon {
- color: #faad14;
- }
- }
- }
-
- .preset-row {
- margin-bottom: 30px;
-
- .preset-radio-group {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: 15px;
-
- :deep(.t-radio) {
- border: 2px solid #e8f5e8;
- border-radius: 8px;
- padding: 15px;
- transition: all 0.3s ease;
- cursor: pointer;
- background: white;
-
- &:hover {
- border-color: #07c05f;
- background-color: #f8fdf8;
- box-shadow: 0 4px 12px rgba(7, 192, 95, 0.1);
- }
-
- &.t-is-checked {
- border-color: #07c05f;
- background: linear-gradient(135deg, #07c05f, #00a651);
- color: white;
- transform: translateY(-2px);
- box-shadow: 0 6px 20px rgba(7, 192, 95, 0.2);
-
- .preset-title {
- color: white !important;
- }
-
- .preset-desc {
- color: rgba(255, 255, 255, 0.9) !important;
- }
- }
-
- .preset-content {
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- width: 100%;
- }
-
- .preset-title {
- font-weight: 600;
- font-size: 14px;
- color: #333;
- margin-bottom: 4px;
- }
-
- .preset-desc {
- font-size: 12px;
- color: #666;
- line-height: 1.4;
- }
- }
- }
- }
-
- .parameters-grid {
- display: flex;
- flex-direction: column;
- gap: 24px;
- margin-top: 20px;
- padding: 20px 16px;
- background: #fff;
- border-radius: 12px;
- border: 1px solid #edf2f7;
- box-shadow: 0 6px 16px rgba(15, 23, 42, 0.04);
-
- &.disabled-grid {
- opacity: 0.6;
- pointer-events: none;
- background-color: #f8f9fa;
- border-color: #ddd;
- }
-
- .parameter-group {
- .parameter-label {
- font-weight: 600;
- color: #333;
- margin-bottom: 12px;
- font-size: 14px;
- }
-
- .parameter-control {
- display: flex;
- align-items: center;
- gap: 12px;
- margin-bottom: 20px;
-
- .parameter-slider {
- flex: 1;
-
- :deep(.t-slider__rail) {
- background-color: #e8f5e8;
- }
-
- :deep(.t-slider__track) {
- background-color: #07c05f;
- }
-
- :deep(.t-slider__handle) {
- background-color: #07c05f;
- border-color: #07c05f;
- }
- }
-
- .parameter-value {
- font-size: 14px;
- color: #666;
- font-weight: 500;
- min-width: 80px;
- text-align: right;
- white-space: nowrap;
- }
-
- .parameter-select {
- flex: 1;
- }
- }
-
- .parameter-desc {
- font-size: 12px;
- color: #999;
- line-height: 1.4;
- margin-top: 8px;
- }
- }
- }
-
-
- .multimodal-test {
- margin-top: 20px;
- padding: 20px;
- background: #f8fff9;
- border-radius: 10px;
- border: 1px solid #e8f5e8;
-
- h5 {
- font-size: 16px;
- color: #07c05f;
- margin-bottom: 8px;
- font-weight: 600;
- }
-
- .test-desc {
- margin-bottom: 16px;
- font-size: 13px;
- color: #6b7280;
- line-height: 1.4;
- }
-
- .test-area {
- display: flex;
- flex-direction: column;
- gap: 16px;
- }
-
- .upload-section {
- display: flex;
- flex-direction: column;
- gap: 12px;
-
- .upload-buttons {
- display: flex;
- align-items: center;
- gap: 12px;
- flex-wrap: wrap;
- }
- }
-
- .image-preview {
- text-align: center;
- padding: 20px;
- background: white;
- border-radius: 10px;
- border: 1px solid #e8f5e8;
- box-shadow: 0 2px 8px rgba(7, 192, 95, 0.08);
-
- img {
- max-width: 100%;
- max-height: 200px;
- object-fit: contain;
- border-radius: 8px;
- margin-bottom: 12px;
- border: 1px solid #f0f0f0;
- }
-
- .image-meta {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 8px 12px;
- background: #f8fff9;
- border-radius: 6px;
- border: 1px solid #e8f5e8;
-
- .file-name {
- font-weight: 500;
- text-overflow: ellipsis;
- overflow: hidden;
- white-space: nowrap;
- max-width: 70%;
- color: #333;
- font-size: 13px;
- }
-
- .file-size {
- color: #6b7280;
- font-size: 12px;
- font-weight: 500;
- }
- }
- }
-
- .test-button-wrapper {
- text-align: center;
- margin-top: 16px;
- padding: 12px 20px;
- background: #f8fff9;
- border-radius: 8px;
- border: 1px solid #e8f5e8;
-
- .t-button {
- min-width: 100px;
- height: 32px;
- font-weight: 500;
- font-size: 13px;
- }
- }
-
- .test-result {
- background: white;
- border-radius: 10px;
- padding: 20px;
- border: 1px solid #e8f5e8;
- box-shadow: 0 2px 8px rgba(7, 192, 95, 0.08);
-
- h6 {
- font-size: 15px;
- margin-bottom: 16px;
- color: #07c05f;
- font-weight: 600;
- padding-bottom: 8px;
- border-bottom: 2px solid #f0fdf4;
- }
-
- .result-item {
- margin-bottom: 16px;
-
- label {
- display: block;
- font-weight: 600;
- margin-bottom: 8px;
- color: #333;
- font-size: 14px;
- }
-
- .result-text {
- background: #f8fff9;
- padding: 12px 16px;
- border-radius: 8px;
- color: #333;
- white-space: pre-wrap;
- max-height: 120px;
- overflow-y: auto;
- border: 1px solid #e8f5e8;
- font-size: 13px;
- line-height: 1.5;
- }
- }
-
- .result-time {
- text-align: right;
- color: #6b7280;
- font-size: 12px;
- margin-top: 12px;
- padding: 8px 12px;
- background: #f8f9fa;
- border-radius: 6px;
- border: 1px solid #e9ecef;
- }
-
- .result-error {
- color: #e34d59;
-
- .error-msg {
- display: flex;
- align-items: center;
- gap: 8px;
- background: #fff2f0;
- padding: 12px 16px;
- border-radius: 8px;
- border: 1px solid #ffccc7;
- font-size: 13px;
- line-height: 1.4;
- }
- }
- }
- }
-}
-</style>
\ No newline at end of file
diff --git a/frontend/src/views/initialization/InitializationContent.vue b/frontend/src/views/initialization/InitializationContent.vue
index 1cd8b636e..5552a37d4 100644
--- a/frontend/src/views/initialization/InitializationContent.vue
+++ b/frontend/src/views/initialization/InitializationContent.vue
@@ -1,5 +1,6 @@
<template>
- <div class="initialization-content">
+ <div class="settings-page-container">
+ <div class="initialization-content">
<!-- 顶部Ollama服务状态 -->
<div class="ollama-summary-card">
<div class="summary-header">
@@ -30,6 +31,21 @@
<!-- 主配置表单 -->
<t-form ref="form" :data="formData" :rules="rules" @submit.prevent layout="vertical">
+ <!-- 知识库基本信息配置区域 (仅在知识库设置模式下显示) -->
+ <div v-if="props.isKbSettings" class="config-section">
+ <h3><t-icon name="folder" class="section-icon" />知识库基本信息</h3>
+ <div class="form-row">
+ <t-form-item label="知识库名称" name="kbName" :required="true">
+ <t-input v-model="formData.kbName" placeholder="请输入知识库名称" maxlength="50" show-word-limit />
+ </t-form-item>
+ </div>
+ <div class="form-row">
+ <t-form-item label="知识库描述" name="kbDescription">
+ <t-textarea v-model="formData.kbDescription" placeholder="请输入知识库描述" maxlength="200" show-word-limit :autosize="{ minRows: 3, maxRows: 6 }" />
+ </t-form-item>
+ </div>
+ </div>
+
<!-- LLM 大语言模型配置区域 -->
<div class="config-section">
<h3><t-icon name="chat" class="section-icon" />LLM 大语言模型配置</h3>
@@ -709,7 +725,7 @@
<t-button theme="primary" type="button" size="large"
:loading="submitting" :disabled="!canSubmit || isSubmitDebounced"
@click="handleSubmit">
- {{ isUpdateMode ? '更新配置信息' : '完成配置' }}
+ {{ props.isKbSettings ? '更新知识库设置' : (isUpdateMode ? '更新配置信息' : '完成配置') }}
</t-button>
<!-- 提交状态提示 -->
@@ -725,6 +741,7 @@
</div>
</div>
</t-form>
+ </div>
</div>
</template>
@@ -733,15 +750,15 @@
* 导入必要的 Vue 组合式 API 和外部依赖
*/
import { ref, reactive, computed, watch, onMounted, onUnmounted, nextTick } from 'vue';
-import { useRouter } from 'vue-router';
+import { useRouter, useRoute } from 'vue-router';
import { MessagePlugin } from 'tdesign-vue-next';
import {
- initializeSystem,
+ initializeSystemByKB,
checkOllamaStatus,
checkOllamaModels,
downloadOllamaModel,
getDownloadProgress,
- getCurrentConfig,
+ getCurrentConfigByKB,
checkRemoteModel,
type DownloadTask,
checkRerankModel,
@@ -749,10 +766,22 @@ import {
listOllamaModels,
testEmbeddingModel
} from '@/api/initialization';
+import { getKnowledgeBaseById } from '@/api/knowledge-base';
import { useAuthStore } from '@/stores/auth';
const router = useRouter();
+const route = useRoute();
const authStore = useAuthStore();
+
+// 接收props,判断是否为知识库设置模式
+const props = defineProps<{
+ isKbSettings?: boolean;
+}>();
+
+// 获取当前知识库ID(如果是知识库设置模式)
+const currentKbId = computed(() => {
+ return props.isKbSettings ? (route.params.kbId as string) : null;
+});
type TFormRef = {
validate: (fields?: string[] | undefined) => Promise<true | any>;
clearValidate?: (fields?: string | string[]) => void;
@@ -824,6 +853,9 @@ const modelStatus = reactive({
// 表单数据
const formData = reactive({
+ // 知识库基本信息 (仅在知识库设置模式下使用)
+ kbName: '',
+ kbDescription: '',
llm: {
source: 'local',
modelName: '',
@@ -867,8 +899,8 @@ const formData = reactive({
}
},
documentSplitting: {
- chunkSize: 1000,
- chunkOverlap: 200,
+ chunkSize: 512,
+ chunkOverlap: 100,
separators: ['\n\n', '\n', '。', '!', '?', ';', ';']
}
});
@@ -880,7 +912,7 @@ const inputDebounceTimers = reactive<Record<string, any>>({});
const embeddingDimDetecting = ref(false);
// 预设配置选择
-const selectedPreset = ref('balanced');
+const selectedPreset = ref('precision');
// 分隔符选项
const separatorOptions = [
@@ -1011,6 +1043,14 @@ const validateEmbeddingDimension = (val: any) => {
// 表单验证规则
const rules = {
+ // 知识库基本信息验证 (仅在知识库设置模式下使用)
+ 'kbName': [
+ { required: (t: any) => props.isKbSettings, message: '请输入知识库名称', type: 'error' },
+ { min: 1, max: 50, message: '知识库名称长度应在1-50个字符之间', type: 'error' }
+ ],
+ 'kbDescription': [
+ { max: 200, message: '知识库描述长度不能超过200个字符', type: 'error' }
+ ],
'llm.modelName': [{ required: true, message: '请输入LLM模型名称', type: 'error' }],
'llm.baseUrl': [
{ required: (t: any) => formData.llm.source === 'remote', message: '请输入BaseURL', type: 'error' }
@@ -1191,7 +1231,22 @@ const startProgressPolling = (type: 'llm' | 'embedding' | 'vlm', taskId: string,
// 配置回填
const loadCurrentConfig = async () => {
try {
- const config = await getCurrentConfig();
+ // 如果是知识库设置模式,先加载知识库基本信息
+ if (props.isKbSettings && currentKbId.value) {
+ try {
+ const kbInfo = await getKnowledgeBaseById(currentKbId.value);
+ if (kbInfo && kbInfo.data) {
+ formData.kbName = kbInfo.data.name || '';
+ formData.kbDescription = kbInfo.data.description || '';
+ }
+ } catch (error) {
+ console.error('获取知识库信息失败:', error);
+ MessagePlugin.error('获取知识库信息失败');
+ }
+ }
+
+ // 根据是否为知识库设置模式选择不同的API
+ const config = await getCurrentConfigByKB(currentKbId.value);
// 设置hasFiles状态
hasFiles.value = config.hasFiles || false;
@@ -1234,6 +1289,9 @@ const loadCurrentConfig = async () => {
} else {
selectedPreset.value = 'custom';
}
+ } else {
+ // 如果没有文档分割配置,确保使用默认的precision模式
+ selectedPreset.value = 'precision';
}
// 在配置加载完成后,检查模型状态
@@ -1883,21 +1941,43 @@ const handleSubmit = async () => {
submitting.value = true;
+ // 如果是知识库设置模式,先更新知识库基本信息
+ if (props.isKbSettings && currentKbId.value) {
+ try {
+ const { updateKnowledgeBase } = await import('@/api/knowledge-base');
+ await updateKnowledgeBase(currentKbId.value, {
+ name: formData.kbName,
+ description: formData.kbDescription,
+ config: {} // 空的config对象,因为这里只更新基本信息
+ });
+ } catch (error) {
+ console.error('更新知识库基本信息失败:', error);
+ MessagePlugin.error('更新知识库基本信息失败');
+ return;
+ }
+ }
+
// 确保embedding.dimension是数字类型
if (formData.embedding.dimension) {
formData.embedding.dimension = Number(formData.embedding.dimension);
}
- // 直接使用formData,API期望原始结构
- const result = await initializeSystem(formData);
+ // 根据是否为知识库设置模式选择不同的API
+ const result = await initializeSystemByKB(currentKbId.value, formData);
if (result.success) {
- MessagePlugin.success(isUpdateMode.value ? '配置更新成功' : '系统初始化完成');
+ MessagePlugin.success(props.isKbSettings ? '知识库设置更新成功' : (isUpdateMode.value ? '配置更新成功' : '系统初始化完成'));
- // 如果是初始化模式,跳转到主页面
- if (!isUpdateMode.value) {
+ // 根据不同模式进行跳转
+ if (props.isKbSettings && currentKbId.value) {
+ // 知识库设置模式,跳转回知识库详情页面
+ setTimeout(() => {
+ router.push(`/platform/knowledge-bases/${currentKbId.value}`);
+ }, 1500);
+ } else if (!isUpdateMode.value) {
+ // 初始化模式,跳转到知识库列表页面
setTimeout(() => {
- router.push('/platform/knowledgeBase');
+ router.push('/platform/knowledge-bases');
}, 1500);
}
} else {
@@ -1940,7 +2020,18 @@ onMounted(async () => {
</script>
<style lang="less" scoped>
+.settings-page-container {
+ width: 100%;
+ height: 100vh;
+ overflow-y: auto;
+ background-color: #f5f7fa;
+ padding: 24px;
+ box-sizing: border-box;
+}
+
.initialization-content {
+ max-width: 1200px;
+ margin: 0 auto;
padding: 0;
.ollama-summary-card {
@@ -2168,10 +2259,10 @@ onMounted(async () => {
.remote-config {
margin-top: 20px;
- padding: 20px;
- background: #f9fcff;
- border-radius: 12px;
- border: 1px solid #edf2f7;
+ // padding: 20px;
+ // background: #f9fcff;
+ // border-radius: 12px;
+ // border: 1px solid #edf2f7;
}
.url-input-with-check {
@@ -2272,11 +2363,11 @@ onMounted(async () => {
}
.rerank-config, .multimodal-config {
- margin-top: 20px;
- padding: 20px;
- background: #f9fcff;
- border-radius: 12px;
- border: 1px solid #edf2f7;
+ // margin-top: 20px;
+ // padding: 20px;
+ // background: #f9fcff;
+ // border-radius: 12px;
+ // border: 1px solid #edf2f7;
h4 {
color: #333;
@@ -2436,11 +2527,11 @@ onMounted(async () => {
}
.multimodal-test {
- margin-top: 20px;
- padding: 20px;
- background: #f8fff9;
- border-radius: 10px;
- border: 1px solid #e8f5e8;
+ // margin-top: 20px;
+ // padding: 20px;
+ // background: #f8fff9;
+ // border-radius: 10px;
+ // border: 1px solid #e8f5e8;
h5 {
font-size: 16px;
@@ -2476,12 +2567,12 @@ onMounted(async () => {
}
.image-preview {
- text-align: center;
- padding: 20px;
- background: white;
- border-radius: 10px;
- border: 1px solid #e8f5e8;
- box-shadow: 0 2px 8px rgba(7, 192, 95, 0.08);
+ // text-align: center;
+ // padding: 20px;
+ // background: white;
+ // border-radius: 10px;
+ // border: 1px solid #e8f5e8;
+ // box-shadow: 0 2px 8px rgba(7, 192, 95, 0.08);
img {
max-width: 100%;
@@ -2521,11 +2612,11 @@ onMounted(async () => {
.test-button-wrapper {
text-align: center;
- margin-top: 16px;
- padding: 12px 20px;
- background: #f8fff9;
- border-radius: 8px;
- border: 1px solid #e8f5e8;
+ // margin-top: 16px;
+ // padding: 12px 20px;
+ // background: #f8fff9;
+ // border-radius: 8px;
+ // border: 1px solid #e8f5e8;
.t-button {
min-width: 100px;
diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue
index 1278b7108..ae68163fc 100644
--- a/frontend/src/views/knowledge/KnowledgeBase.vue
+++ b/frontend/src/views/knowledge/KnowledgeBase.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { ref, onMounted, watch, reactive } from "vue";
+import { ref, onMounted, onUnmounted, watch, reactive, computed } from "vue";
import DocContent from "@/components/doc-content.vue";
import InputField from "@/components/Input-field.vue";
import useKnowledgeBase from '@/hooks/useKnowledgeBase';
@@ -7,17 +7,21 @@ import { useRoute, useRouter } from 'vue-router';
import EmptyKnowledge from '@/components/empty-knowledge.vue';
import { getSessionsList, createSessions, generateSessionsTitle } from "@/api/chat/index";
import { useMenuStore } from '@/stores/menu';
-import { getTestData } from '@/utils/request';
+import { MessagePlugin } from 'tdesign-vue-next';
const usemenuStore = useMenuStore();
const router = useRouter();
import {
batchQueryKnowledge,
+ listKnowledgeFiles,
} from "@/api/knowledge-base/index";
-let { cardList, total, moreIndex, details, getKnowled, delKnowledge, openMore, onVisibleChange, getCardDetails, getfDetails } = useKnowledgeBase()
+import { formatStringDate } from "@/utils/index";
+const route = useRoute();
+const kbId = computed(() => (route.params as any).kbId as string || '');
+let { cardList, total, moreIndex, details, getKnowled, delKnowledge, openMore, onVisibleChange, getCardDetails, getfDetails } = useKnowledgeBase(kbId.value)
let isCardDetails = ref(false);
-let timeout = null;
+let timeout: ReturnType<typeof setInterval> | null = null;
let delDialog = ref(false)
-let knowledge = ref({})
+let knowledge = ref<KnowledgeCard>({ id: '', parse_status: '' })
let knowledgeIndex = ref(-1)
let knowledgeScroll = ref()
let page = 1;
@@ -29,29 +33,93 @@ const getPageSize = () => {
pageSize = Math.max(35, itemsInView);
}
getPageSize()
+// 直接调用 API 获取知识库文件列表
+const loadKnowledgeFiles = async (kbIdValue: string) => {
+ if (!kbIdValue) return;
+
+ try {
+ const result = await listKnowledgeFiles(kbIdValue, { page: 1, page_size: pageSize });
+
+ // 由于响应拦截器已经返回了 data,所以 result 就是响应的 data 部分
+ // 按照 useKnowledgeBase hook 中的方式处理
+ const { data, total: totalResult } = result as any;
+
+ if (!data || !Array.isArray(data)) {
+ console.error('Invalid data format. Expected array, got:', typeof data, data);
+ return;
+ }
+
+ const cardList_ = data.map((item: any) => {
+ item["file_name"] = item.file_name.substring(
+ 0,
+ item.file_name.lastIndexOf(".")
+ );
+ return {
+ ...item,
+ updated_at: formatStringDate(new Date(item.updated_at)),
+ isMore: false,
+ file_type: item.file_type.toLocaleUpperCase(),
+ };
+ });
+
+ cardList.value = cardList_ as any[];
+ total.value = totalResult;
+ } catch (err) {
+ console.error('Failed to load knowledge files:', err);
+ }
+};
+
+// 监听路由参数变化,重新获取知识库内容
+watch(() => kbId.value, (newKbId, oldKbId) => {
+ if (newKbId && newKbId !== oldKbId) {
+ loadKnowledgeFiles(newKbId);
+ }
+}, { immediate: false });
+
+// 监听文件上传事件
+const handleFileUploaded = (event: CustomEvent) => {
+ const uploadedKbId = event.detail.kbId;
+ console.log('接收到文件上传事件,上传的知识库ID:', uploadedKbId, '当前知识库ID:', kbId.value);
+ if (uploadedKbId && uploadedKbId === kbId.value) {
+ console.log('匹配当前知识库,开始刷新文件列表');
+ // 如果上传的文件属于当前知识库,使用 loadKnowledgeFiles 刷新文件列表
+ loadKnowledgeFiles(uploadedKbId);
+ }
+};
+
onMounted(() => {
getKnowled({ page: 1, page_size: pageSize });
+
+ // 监听文件上传事件
+ window.addEventListener('knowledgeFileUploaded', handleFileUploaded as EventListener);
+});
+
+onUnmounted(() => {
+ window.removeEventListener('knowledgeFileUploaded', handleFileUploaded as EventListener);
});
watch(() => cardList.value, (newValue) => {
let analyzeList = [];
analyzeList = newValue.filter(item => {
return item.parse_status == 'pending' || item.parse_status == 'processing';
})
- clearInterval(timeout);
- timeout = null;
+ if (timeout !== null) {
+ clearInterval(timeout);
+ timeout = null;
+ }
if (analyzeList.length) {
updateStatus(analyzeList)
}
}, { deep: true })
-const updateStatus = (analyzeList) => {
+type KnowledgeCard = { id: string; parse_status: string; description?: string; file_name?: string; updated_at?: string; file_type?: string; isMore?: boolean };
+const updateStatus = (analyzeList: KnowledgeCard[]) => {
let query = ``;
for (let i = 0; i < analyzeList.length; i++) {
query += `ids=${analyzeList[i].id}&`;
}
timeout = setInterval(() => {
- batchQueryKnowledge(query).then((result) => {
+ batchQueryKnowledge(query).then((result: any) => {
if (result.success && result.data) {
- result.data.forEach(item => {
+ (result.data as KnowledgeCard[]).forEach((item: KnowledgeCard) => {
if (item.parse_status == 'failed' || item.parse_status == 'completed') {
let index = cardList.value.findIndex(card => card.id == item.id);
if (index != -1) {
@@ -70,12 +138,12 @@ const updateStatus = (analyzeList) => {
const closeDoc = () => {
isCardDetails.value = false;
};
-const openCardDetails = (item) => {
+const openCardDetails = (item: KnowledgeCard) => {
isCardDetails.value = true;
getCardDetails(item);
};
-const delCard = (index, item) => {
+const delCard = (index: number, item: KnowledgeCard) => {
knowledgeIndex.value = index;
knowledge.value = item;
delDialog.value = true;
@@ -94,7 +162,7 @@ const handleScroll = () => {
}
}
};
-const getDoc = (page) => {
+const getDoc = (page: number) => {
getfDetails(details.id, page)
};
@@ -108,51 +176,36 @@ const sendMsg = (value: string) => {
};
const getTitle = (session_id: string, value: string) => {
- let obj = { title: '新会话', path: `chat/${session_id}`, id: session_id, isMore: false, isNoTitle: true };
+ let obj = { title: '新会话', path: `chat/${kbId.value}/${session_id}`, id: session_id, isMore: false, isNoTitle: true };
usemenuStore.updataMenuChildren(obj);
usemenuStore.changeIsFirstSession(true);
usemenuStore.changeFirstQuery(value);
- router.push(`/platform/chat/${session_id}`);
+ router.push(`/platform/chat/${kbId.value}/${session_id}`);
};
async function createNewSession(value: string): Promise<void> {
- // 从localStorage获取设置中的知识库ID
- const settingsStr = localStorage.getItem("WeKnora_settings");
- let knowledgeBaseId = "";
+ // 优先使用当前页面的知识库ID
+ let sessionKbId = kbId.value;
- if (settingsStr) {
- try {
- const settings = JSON.parse(settingsStr);
- if (settings.knowledgeBaseId) {
- knowledgeBaseId = settings.knowledgeBaseId;
- createSessions({ knowledge_base_id: knowledgeBaseId }).then(res => {
- if (res.data && res.data.id) {
- getTitle(res.data.id, value);
- } else {
- // 错误处理
- console.error("创建会话失败");
- }
- }).catch(error => {
- console.error("创建会话出错:", error);
- });
- return;
+ // 如果当前页面没有知识库ID,尝试从localStorage获取设置中的知识库ID
+ if (!sessionKbId) {
+ const settingsStr = localStorage.getItem("WeKnora_settings");
+ if (settingsStr) {
+ try {
+ const settings = JSON.parse(settingsStr);
+ sessionKbId = settings.knowledgeBaseId;
+ } catch (e) {
+ console.error("解析设置失败:", e);
}
- } catch (e) {
- console.error("解析设置失败:", e);
}
}
- // 如果设置中没有知识库ID,则使用测试数据
- const testData = getTestData();
- if (!testData || !testData.knowledge_bases || testData.knowledge_bases.length === 0) {
- console.error("测试数据未初始化或不包含知识库");
+ if (!sessionKbId) {
+ MessagePlugin.warning("请先选择一个知识库");
return;
}
-
- // 使用第一个知识库ID
- knowledgeBaseId = testData.knowledge_bases[0].id;
-
- createSessions({ knowledge_base_id: knowledgeBaseId }).then(res => {
+
+ createSessions({ knowledge_base_id: sessionKbId }).then(res => {
if (res.data && res.data.id) {
getTitle(res.data.id, value);
} else {
diff --git a/frontend/src/views/knowledge/KnowledgeBaseList.vue b/frontend/src/views/knowledge/KnowledgeBaseList.vue
new file mode 100644
index 000000000..cb8ecc98a
--- /dev/null
+++ b/frontend/src/views/knowledge/KnowledgeBaseList.vue
@@ -0,0 +1,234 @@
+<template>
+ <div class="kb-list-container">
+ <div class="header">
+ <h2>知识库</h2>
+ <t-button theme="primary" @click="openCreate">新建知识库</t-button>
+ </div>
+
+ <!-- 未初始化知识库提示 -->
+ <div v-if="hasUninitializedKbs" class="warning-banner">
+ <t-icon name="info-circle" size="16px" />
+ <span>部分知识库尚未初始化,需要先在设置中配置模型信息才能添加知识文档</span>
+ </div>
+ <t-table :data="kbs" :columns="columns" row-key="id" size="medium" hover>
+ <template #status="{ row }">
+ <div class="status-cell">
+ <t-tag
+ :theme="isInitialized(row) ? 'success' : 'warning'"
+ size="small"
+ >
+ {{ isInitialized(row) ? '已初始化' : '未初始化' }}
+ </t-tag>
+ <t-tooltip
+ v-if="!isInitialized(row)"
+ content="需要先在设置中配置模型信息才能添加知识"
+ placement="top"
+ >
+ <span class="warning-icon">⚠</span>
+ </t-tooltip>
+ </div>
+ </template>
+ <template #description="{ row }">
+ <div class="description-text">{{ row.description || '暂无描述' }}</div>
+ </template>
+ <template #op="{ row }">
+ <t-space size="small">
+ <t-button
+ size="small"
+ @click="goDetail(row.id)"
+ :disabled="!isInitialized(row)"
+ :theme="isInitialized(row) ? 'primary' : 'default'"
+ :variant="isInitialized(row) ? 'base' : 'outline'"
+ :title="!isInitialized(row) ? '请先在设置中配置模型信息' : ''"
+ >
+ 文档
+ </t-button>
+ <t-button size="small" variant="outline" @click="goSettings(row.id)">设置</t-button>
+ <t-popconfirm content="确认删除该知识库?" @confirm="remove(row.id)">
+ <t-button size="small" theme="danger" variant="text">删除</t-button>
+ </t-popconfirm>
+ </t-space>
+ </template>
+ </t-table>
+
+ <t-dialog v-model:visible="createVisible" header="新建知识库" :footer="false">
+ <t-form :data="createForm" @submit="create">
+ <t-form-item label="名称" name="name" :rules="[{ required: true, message: '请输入名称' }]">
+ <t-input v-model="createForm.name" />
+ </t-form-item>
+ <t-form-item label="描述" name="description">
+ <t-textarea v-model="createForm.description" />
+ </t-form-item>
+ <t-form-item>
+ <t-space>
+ <t-button theme="primary" type="submit" :loading="creating">创建</t-button>
+ <t-button variant="outline" @click="createVisible = false">取消</t-button>
+ </t-space>
+ </t-form-item>
+ </t-form>
+ </t-dialog>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { onMounted, reactive, ref, computed } from 'vue'
+import { useRouter } from 'vue-router'
+import { MessagePlugin } from 'tdesign-vue-next'
+import { listKnowledgeBases, createKnowledgeBase, deleteKnowledgeBase } from '@/api/knowledge-base'
+import { formatStringDate } from '@/utils/index'
+
+const router = useRouter()
+
+interface KB {
+ id: string;
+ name: string;
+ description?: string;
+ updated_at?: string;
+ embedding_model_id?: string;
+ summary_model_id?: string;
+}
+const kbs = ref<KB[]>([])
+const loading = ref(false)
+
+const columns = [
+ { colKey: 'name', title: '名称' },
+ { colKey: 'description', title: '描述', cell: 'description', width: 300 },
+ { colKey: 'status', title: '状态', cell: 'status', width: 100 },
+ { colKey: 'updated_at', title: '更新时间' },
+ { colKey: 'op', title: '操作', cell: 'op', width: 220 },
+]
+
+const fetchList = () => {
+ loading.value = true
+ listKnowledgeBases().then((res: any) => {
+ const data = res.data || []
+ // 格式化时间
+ kbs.value = data.map((kb: KB) => ({
+ ...kb,
+ updated_at: kb.updated_at ? formatStringDate(new Date(kb.updated_at)) : ''
+ }))
+ }).finally(() => loading.value = false)
+}
+
+onMounted(fetchList)
+
+const createVisible = ref(false)
+const creating = ref(false)
+const createForm = reactive({ name: '', description: '' })
+const openCreate = () => {
+ createForm.name = ''
+ createForm.description = ''
+ createVisible.value = true
+}
+const create = () => {
+ if (!createForm.name) return
+ creating.value = true
+ const chunking_config = {
+ chunk_size: 512,
+ chunk_overlap: 100,
+ separators: ['.', '?', '!', '。', '?', '!'],
+ enable_multimodal: false
+ }
+ createKnowledgeBase({ name: createForm.name, description: createForm.description, chunking_config }).then((res: any) => {
+ if (res.success) {
+ MessagePlugin.success('创建成功')
+ createVisible.value = false
+ fetchList()
+ } else {
+ MessagePlugin.error(res.message || '创建失败')
+ }
+ }).catch((e: any) => {
+ MessagePlugin.error(e?.message || '创建失败')
+ }).finally(() => creating.value = false)
+}
+
+const remove = (id: string) => {
+ deleteKnowledgeBase(id).then((res: any) => {
+ if (res.success) {
+ MessagePlugin.success('已删除')
+ fetchList()
+ } else {
+ MessagePlugin.error(res.message || '删除失败')
+ }
+ }).catch((e: any) => MessagePlugin.error(e?.message || '删除失败'))
+}
+
+const isInitialized = (kb: KB) => {
+ return !!(kb.embedding_model_id && kb.embedding_model_id !== '' &&
+ kb.summary_model_id && kb.summary_model_id !== '')
+}
+
+// 计算是否有未初始化的知识库
+const hasUninitializedKbs = computed(() => {
+ return kbs.value.some(kb => !isInitialized(kb))
+})
+
+const goDetail = (id: string) => {
+ router.push(`/platform/knowledge-bases/${id}`)
+}
+const goSettings = (id: string) => {
+ router.push(`/platform/knowledge-bases/${id}/settings`)
+}
+</script>
+
+<style scoped lang="less">
+.kb-list-container {
+ padding: 20px;
+ background: #fff;
+ margin: 0 20px 0 20px;
+ height: calc(100vh);
+ overflow-y: auto;
+ box-sizing: border-box;
+ flex: 1;
+}
+.header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 16px;
+ h2 { margin: 0; font-size: 20px; font-weight: 600; }
+}
+
+.warning-banner {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 12px 16px;
+ margin-bottom: 16px;
+ background: #fff7e6;
+ border: 1px solid #ffd591;
+ border-radius: 6px;
+ color: #d46b08;
+ font-size: 14px;
+
+ .t-icon {
+ color: #d46b08;
+ flex-shrink: 0;
+ }
+}
+
+.status-cell {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+
+ .warning-icon {
+ color: #ff8800;
+ cursor: pointer;
+ font-size: 16px;
+ font-weight: bold;
+ transition: color 0.2s;
+
+ &:hover {
+ color: #d46b08;
+ }
+ }
+}
+
+.description-cell {
+ .description-text {
+ color: #000000e6;
+ font-size: 14px;
+ }
+}
+</style>
diff --git a/frontend/src/views/settings/SystemSettings.vue b/frontend/src/views/settings/SystemSettings.vue
index 730b3d04f..17ba9e1c5 100644
--- a/frontend/src/views/settings/SystemSettings.vue
+++ b/frontend/src/views/settings/SystemSettings.vue
@@ -2,23 +2,109 @@
<div class="system-settings-container">
<!-- 页面标题区域 -->
<div class="settings-header">
- <h2>系统设置</h2>
- <p class="settings-subtitle">管理和更新系统模型与服务配置</p>
+ <h2>{{ isKbSettings ? '知识库设置' : '系统设置' }}</h2>
+ <p class="settings-subtitle">{{ isKbSettings ? '配置该知识库的模型与文档切分参数' : '管理和更新系统模型与服务配置' }}</p>
</div>
<!-- 配置内容 -->
<div class="settings-content">
- <!-- 直接引用初始化配置组件的内容,不使用外层卡片包装 -->
- <InitializationContent />
+ <!-- 系统设置:使用初始化配置 -->
+ <InitializationContent v-if="!isKbSettings" />
+ <!-- 知识库设置:基础信息与文档切分配置 -->
+ <div v-else>
+ <t-form :data="kbForm" @submit="saveKb">
+ <div class="config-section">
+ <h3><span class="section-icon">⚙️</span>基础信息</h3>
+ <t-form-item label="名称" name="name" :rules="[{ required: true, message: '请输入名称' }]">
+ <t-input v-model="kbForm.name" />
+ </t-form-item>
+ <t-form-item label="描述" name="description">
+ <t-textarea v-model="kbForm.description" />
+ </t-form-item>
+ </div>
+ <div class="config-section">
+ <h3><span class="section-icon">📄</span>文档切分</h3>
+ <t-row :gutter="16">
+ <t-col :span="6">
+ <t-form-item label="Chunk Size" name="chunkSize">
+ <t-input-number v-model="kbForm.config.chunking_config.chunk_size" :min="1" />
+ </t-form-item>
+ </t-col>
+ <t-col :span="6">
+ <t-form-item label="Chunk Overlap" name="chunkOverlap">
+ <t-input-number v-model="kbForm.config.chunking_config.chunk_overlap" :min="0" />
+ </t-form-item>
+ </t-col>
+ </t-row>
+ </div>
+ <div class="submit-section">
+ <t-button theme="primary" type="submit" :loading="saving">保存</t-button>
+ </div>
+ </t-form>
+ </div>
</div>
</div>
</template>
<script setup lang="ts">
-import { defineAsyncComponent } from 'vue'
+import { defineAsyncComponent, onMounted, reactive, ref } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { MessagePlugin } from 'tdesign-vue-next'
+import { getKnowledgeBaseById, updateKnowledgeBase } from '@/api/knowledge-base'
// 异步加载初始化配置组件
const InitializationContent = defineAsyncComponent(() => import('../initialization/InitializationContent.vue'))
+
+const route = useRoute()
+const router = useRouter()
+const isKbSettings = ref<boolean>(false)
+
+interface KbForm {
+ name: string
+ description?: string
+ config: { chunking_config: { chunk_size: number; chunk_overlap: number } }
+}
+const kbForm = reactive<KbForm>({
+ name: '',
+ description: '',
+ config: { chunking_config: { chunk_size: 512, chunk_overlap: 64 } }
+})
+const saving = ref(false)
+
+const loadKb = () => {
+ const kbId = (route.params as any).kbId as string
+ if (!kbId) return
+ getKnowledgeBaseById(kbId).then((res: any) => {
+ if (res?.data) {
+ kbForm.name = res.data.name
+ kbForm.description = res.data.description
+ const cc = res.data.chunking_config || {}
+ kbForm.config.chunking_config.chunk_size = cc.chunk_size ?? 512
+ kbForm.config.chunking_config.chunk_overlap = cc.chunk_overlap ?? 64
+ }
+ })
+}
+
+onMounted(() => {
+ isKbSettings.value = route.name === 'knowledgeBaseSettings'
+ if (isKbSettings.value) loadKb()
+})
+
+const saveKb = () => {
+ const kbId = (route.params as any).kbId as string
+ if (!kbId) return
+ saving.value = true
+ updateKnowledgeBase(kbId, { name: kbForm.name, description: kbForm.description, config: { chunking_config: { chunk_size: kbForm.config.chunking_config.chunk_size, chunk_overlap: kbForm.config.chunking_config.chunk_overlap, separators: [], enable_multimodal: false }, image_processing_config: { model_id: '' } } })
+ .then((res: any) => {
+ if (res.success) {
+ MessagePlugin.success('保存成功')
+ } else {
+ MessagePlugin.error(res.message || '保存失败')
+ }
+ })
+ .catch((e: any) => MessagePlugin.error(e?.message || '保存失败'))
+ .finally(() => saving.value = false)
+}
</script>
<style lang="less" scoped>
diff --git a/frontend/src/views/tenant/TenantInfo.vue b/frontend/src/views/tenant/TenantInfo.vue
index 1890cb26c..c15f37945 100644
--- a/frontend/src/views/tenant/TenantInfo.vue
+++ b/frontend/src/views/tenant/TenantInfo.vue
@@ -1,11 +1,34 @@
<template>
<div class="tenant-info-container">
<div class="tenant-header">
- <h2>账户信息</h2>
- <p class="tenant-subtitle">查看和管理您的用户账户和租户配置信息</p>
+ <h2>系统信息</h2>
+ <p class="tenant-subtitle">查看系统版本信息和用户账户配置</p>
</div>
<div class="tenant-content" v-if="!loading && !error">
+ <!-- 系统信息卡片 -->
+ <t-card class="info-card" :bordered="false">
+ <template #header>
+ <div class="card-title">系统信息</div>
+ </template>
+ <div class="info-content">
+ <t-descriptions :column="1" layout="vertical">
+ <t-descriptions-item label="版本号">
+ {{ systemInfo?.version || '未知' }}
+ <span v-if="systemInfo?.commit_id" class="commit-info">
+ ({{ systemInfo.commit_id }})
+ </span>
+ </t-descriptions-item>
+ <t-descriptions-item label="构建时间" v-if="systemInfo?.build_time">
+ {{ systemInfo.build_time }}
+ </t-descriptions-item>
+ <t-descriptions-item label="Go版本" v-if="systemInfo?.go_version">
+ {{ systemInfo.go_version }}
+ </t-descriptions-item>
+ </t-descriptions>
+ </div>
+ </t-card>
+
<!-- 用户信息卡片 -->
<t-card class="info-card" :bordered="false">
<template #header>
@@ -161,10 +184,12 @@
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { getCurrentUser, type TenantInfo, type UserInfo } from '@/api/auth'
+import { getSystemInfo, type SystemInfo } from '@/api/system'
// 响应式数据
const tenantInfo = ref<TenantInfo | null>(null)
const userInfo = ref<UserInfo | null>(null)
+const systemInfo = ref<SystemInfo | null>(null)
const loading = ref(true)
const error = ref('')
const showApiKey = ref(false)
@@ -192,12 +217,21 @@ const loadTenantInfo = async () => {
loading.value = true
error.value = ''
- const response = await getCurrentUser()
- if (response.success && response.data) {
- userInfo.value = response.data.user
- tenantInfo.value = response.data.tenant
+ // 并行获取用户信息和系统信息
+ const [userResponse, systemResponse] = await Promise.all([
+ getCurrentUser(),
+ getSystemInfo().catch(() => ({ data: null })) // 系统信息获取失败不影响页面显示
+ ])
+
+ if (userResponse.success && userResponse.data) {
+ userInfo.value = userResponse.data.user
+ tenantInfo.value = userResponse.data.tenant
} else {
- error.value = response.message || '获取用户信息失败'
+ error.value = userResponse.message || '获取用户信息失败'
+ }
+
+ if (systemResponse.data) {
+ systemInfo.value = systemResponse.data
}
} catch (err: any) {
error.value = err.message || '网络错误,请稍后重试'
@@ -349,7 +383,7 @@ onMounted(() => {
.card-title {
font-size: 16px;
font-weight: 600;
- color: #000000;
+ color: #07C05F;
}
.card-header-with-actions {
@@ -457,6 +491,12 @@ onMounted(() => {
gap: 12px;
}
+ .commit-info {
+ color: #666;
+ font-size: 12px;
+ margin-left: 8px;
+ }
+
.doc-actions {
:deep(.t-space) {
flex-direction: column;
@@ -471,7 +511,6 @@ onMounted(() => {
/* 覆盖TDesign组件样式 */
:deep(.t-card) {
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
border: 1px solid #e5e7eb;
}
diff --git a/internal/application/service/evaluation.go b/internal/application/service/evaluation.go
index 84c4a4727..391a580f0 100644
--- a/internal/application/service/evaluation.go
+++ b/internal/application/service/evaluation.go
@@ -3,6 +3,7 @@ package service
import (
"context"
"errors"
+ "fmt"
"runtime"
"sync"
"time"
@@ -30,7 +31,7 @@ type EvaluationService struct {
knowledgeBaseService interfaces.KnowledgeBaseService // Service for knowledge base operations
knowledgeService interfaces.KnowledgeService // Service for knowledge operations
sessionService interfaces.SessionService // Service for chat sessions
- testData *TestDataService // Service for test data
+ modelService interfaces.ModelService // Service for model operations
evaluationMemoryStorage *evaluationMemoryStorage // In-memory storage for evaluation tasks
}
@@ -41,7 +42,7 @@ func NewEvaluationService(
knowledgeBaseService interfaces.KnowledgeBaseService,
knowledgeService interfaces.KnowledgeService,
sessionService interfaces.SessionService,
- testData *TestDataService,
+ modelService interfaces.ModelService,
) interfaces.EvaluationService {
evaluationMemoryStorage := newEvaluationMemoryStorage()
return &EvaluationService{
@@ -50,7 +51,7 @@ func NewEvaluationService(
knowledgeBaseService: knowledgeBaseService,
knowledgeService: knowledgeService,
sessionService: sessionService,
- testData: testData,
+ modelService: modelService,
evaluationMemoryStorage: evaluationMemoryStorage,
}
}
@@ -144,11 +145,32 @@ func (e *EvaluationService) Evaluation(ctx context.Context,
if knowledgeBaseID == "" {
logger.Info(ctx, "No knowledge base ID provided, creating new knowledge base")
// Create new knowledge base with default evaluation settings
+ // 获取默认的嵌入模型和LLM模型
+ models, err := e.modelService.ListModels(ctx)
+ if err != nil {
+ logger.Errorf(ctx, "Failed to list models: %v", err)
+ return nil, err
+ }
+
+ var embeddingModelID, llmModelID string
+ for _, model := range models {
+ if model.Type == types.ModelTypeEmbedding {
+ embeddingModelID = model.ID
+ }
+ if model.Type == types.ModelTypeKnowledgeQA {
+ llmModelID = model.ID
+ }
+ }
+
+ if embeddingModelID == "" || llmModelID == "" {
+ return nil, fmt.Errorf("no default models found for evaluation")
+ }
+
kb, err := e.knowledgeBaseService.CreateKnowledgeBase(ctx, &types.KnowledgeBase{
Name: "evaluation",
Description: "evaluation",
- EmbeddingModelID: e.testData.EmbedModel.GetModelID(),
- SummaryModelID: e.testData.LLMModel.GetModelID(),
+ EmbeddingModelID: embeddingModelID,
+ SummaryModelID: llmModelID,
})
if err != nil {
logger.Errorf(ctx, "Failed to create knowledge base: %v", err)
@@ -186,12 +208,37 @@ func (e *EvaluationService) Evaluation(ctx context.Context,
}
if rerankModelID == "" {
- rerankModelID = e.testData.RerankModel.GetModelID()
- logger.Infof(ctx, "Using default rerank model: %s", rerankModelID)
+ // 获取默认的重排模型
+ models, err := e.modelService.ListModels(ctx)
+ if err == nil {
+ for _, model := range models {
+ if model.Type == types.ModelTypeRerank {
+ rerankModelID = model.ID
+ break
+ }
+ }
+ }
+ if rerankModelID == "" {
+ logger.Warnf(ctx, "No rerank model found, skipping rerank")
+ } else {
+ logger.Infof(ctx, "Using default rerank model: %s", rerankModelID)
+ }
}
if chatModelID == "" {
- chatModelID = e.testData.LLMModel.GetModelID()
+ // 获取默认的LLM模型
+ models, err := e.modelService.ListModels(ctx)
+ if err == nil {
+ for _, model := range models {
+ if model.Type == types.ModelTypeKnowledgeQA {
+ chatModelID = model.ID
+ break
+ }
+ }
+ }
+ if chatModelID == "" {
+ return nil, fmt.Errorf("no default chat model found")
+ }
logger.Infof(ctx, "Using default chat model: %s", chatModelID)
}
diff --git a/internal/application/service/test_data.go b/internal/application/service/test_data.go
deleted file mode 100644
index 49e098de5..000000000
--- a/internal/application/service/test_data.go
+++ /dev/null
@@ -1,444 +0,0 @@
-// Package service 提供应用程序的核心业务逻辑服务层
-// 此包包含了知识库管理、用户租户管理、模型服务等核心功能实现
-package service
-
-import (
- "context"
- "fmt"
- "os"
- "strconv"
-
- "github.com/Tencent/WeKnora/internal/config"
- "github.com/Tencent/WeKnora/internal/logger"
- "github.com/Tencent/WeKnora/internal/models/chat"
- "github.com/Tencent/WeKnora/internal/models/embedding"
- "github.com/Tencent/WeKnora/internal/models/rerank"
- "github.com/Tencent/WeKnora/internal/models/utils/ollama"
- "github.com/Tencent/WeKnora/internal/types"
- "github.com/Tencent/WeKnora/internal/types/interfaces"
-)
-
-// TestDataService 测试数据服务
-// 负责初始化测试环境所需的数据,包括创建测试租户、测试知识库
-// 以及配置必要的模型服务实例
-type TestDataService struct {
- config *config.Config // 应用程序配置
- kbRepo interfaces.KnowledgeBaseRepository // 知识库存储库接口
- tenantService interfaces.TenantService // 租户服务接口
- ollamaService *ollama.OllamaService // Ollama模型服务
- modelService interfaces.ModelService // 模型服务接口
- EmbedModel embedding.Embedder // 嵌入模型实例
- RerankModel rerank.Reranker // 重排模型实例
- LLMModel chat.Chat // 大语言模型实例
-}
-
-// NewTestDataService 创建测试数据服务
-// 注入所需的依赖服务和组件
-func NewTestDataService(
- config *config.Config,
- kbRepo interfaces.KnowledgeBaseRepository,
- tenantService interfaces.TenantService,
- ollamaService *ollama.OllamaService,
- modelService interfaces.ModelService,
-) *TestDataService {
- return &TestDataService{
- config: config,
- kbRepo: kbRepo,
- tenantService: tenantService,
- ollamaService: ollamaService,
- modelService: modelService,
- }
-}
-
-// initTenant 初始化测试租户
-// 通过环境变量获取租户ID,如果租户不存在则创建新租户,否则更新现有租户
-// 同时配置租户的检索引擎参数
-func (s *TestDataService) initTenant(ctx context.Context) error {
- logger.Info(ctx, "Start initializing test tenant")
-
- // 从环境变量获取租户ID
- tenantID := os.Getenv("INIT_TEST_TENANT_ID")
- logger.Infof(ctx, "Test tenant ID from environment: %s", tenantID)
-
- // 将字符串ID转换为uint64
- tenantIDUint, err := strconv.ParseUint(tenantID, 10, 64)
- if err != nil {
- logger.Errorf(ctx, "Failed to parse tenant ID: %v", err)
- return err
- }
-
- // 创建租户配置
- tenantConfig := &types.Tenant{
- Name: "Test Tenant",
- Description: "Test Tenant for Testing",
- RetrieverEngines: types.RetrieverEngines{
- Engines: []types.RetrieverEngineParams{
- {
- RetrieverType: types.KeywordsRetrieverType,
- RetrieverEngineType: types.PostgresRetrieverEngineType,
- },
- {
- RetrieverType: types.VectorRetrieverType,
- RetrieverEngineType: types.PostgresRetrieverEngineType,
- },
- },
- },
- }
-
- // 获取或创建测试租户
- logger.Infof(ctx, "Attempting to get tenant with ID: %d", tenantIDUint)
- tenant, err := s.tenantService.GetTenantByID(ctx, uint(tenantIDUint))
- if err != nil {
- // 租户不存在,创建新租户
- logger.Info(ctx, "Tenant not found, creating a new test tenant")
- tenant, err = s.tenantService.CreateTenant(ctx, tenantConfig)
- if err != nil {
- logger.Errorf(ctx, "Failed to create tenant: %v", err)
- return err
- }
- logger.Infof(ctx, "Created new test tenant with ID: %d", tenant.ID)
- } else {
- // 租户存在,更新检索引擎配置
- logger.Info(ctx, "Test tenant found, updating retriever engines")
- tenant.RetrieverEngines = tenantConfig.RetrieverEngines
- tenant, err = s.tenantService.UpdateTenant(ctx, tenant)
- if err != nil {
- logger.Errorf(ctx, "Failed to update tenant: %v", err)
- return err
- }
- logger.Info(ctx, "Test tenant updated successfully")
- }
-
- logger.Infof(ctx, "Test tenant configured - ID: %d, Name: %s, API Key: %s",
- tenant.ID, tenant.Name, tenant.APIKey)
- return nil
-}
-
-// initKnowledgeBase 初始化测试知识库
-// 从环境变量获取知识库ID,创建或更新知识库
-// 配置知识库的分块策略、嵌入模型和摘要模型
-func (s *TestDataService) initKnowledgeBase(ctx context.Context) error {
- logger.Info(ctx, "Start initializing test knowledge base")
-
- // 检查上下文中的租户ID
- if ctx.Value(types.TenantIDContextKey).(uint) == 0 {
- logger.Warn(ctx, "Tenant ID is 0, skipping knowledge base initialization")
- return nil
- }
-
- // 从环境变量获取知识库ID
- knowledgeBaseID := os.Getenv("INIT_TEST_KNOWLEDGE_BASE_ID")
- logger.Infof(ctx, "Test knowledge base ID from environment: %s", knowledgeBaseID)
-
- // 创建知识库配置
- kbConfig := &types.KnowledgeBase{
- ID: knowledgeBaseID,
- Name: "Test Knowledge Base",
- Description: "Knowledge Base for Testing",
- TenantID: ctx.Value(types.TenantIDContextKey).(uint),
- ChunkingConfig: types.ChunkingConfig{
- ChunkSize: s.config.KnowledgeBase.ChunkSize,
- ChunkOverlap: s.config.KnowledgeBase.ChunkOverlap,
- Separators: s.config.KnowledgeBase.SplitMarkers,
- EnableMultimodal: s.config.KnowledgeBase.ImageProcessing.EnableMultimodal,
- },
- EmbeddingModelID: s.EmbedModel.GetModelID(),
- SummaryModelID: s.LLMModel.GetModelID(),
- RerankModelID: s.RerankModel.GetModelID(),
- }
-
- // 初始化测试知识库
- logger.Info(ctx, "Attempting to get existing knowledge base")
- _, err := s.kbRepo.GetKnowledgeBaseByID(ctx, knowledgeBaseID)
- if err != nil {
- // 知识库不存在,创建新知识库
- logger.Info(ctx, "Knowledge base not found, creating a new one")
- logger.Infof(ctx, "Creating knowledge base with ID: %s, tenant ID: %d",
- kbConfig.ID, kbConfig.TenantID)
-
- if err := s.kbRepo.CreateKnowledgeBase(ctx, kbConfig); err != nil {
- logger.Errorf(ctx, "Failed to create knowledge base: %v", err)
- return err
- }
- logger.Info(ctx, "Knowledge base created successfully")
- } else {
- // 知识库存在,更新配置
- logger.Info(ctx, "Knowledge base found, updating configuration")
- logger.Infof(ctx, "Updating knowledge base with ID: %s", kbConfig.ID)
-
- err = s.kbRepo.UpdateKnowledgeBase(ctx, kbConfig)
- if err != nil {
- logger.Errorf(ctx, "Failed to update knowledge base: %v", err)
- return err
- }
- logger.Info(ctx, "Knowledge base updated successfully")
- }
-
- logger.Infof(ctx, "Test knowledge base configured - ID: %s, Name: %s", kbConfig.ID, kbConfig.Name)
- return nil
-}
-
-// InitializeTestData 初始化测试数据
-// 这是对外暴露的主要方法,负责协调所有测试数据的初始化过程
-// 包括初始化租户、嵌入模型、重排模型、LLM模型和知识库
-func (s *TestDataService) InitializeTestData(ctx context.Context) error {
- logger.Info(ctx, "Start initializing test data")
-
- // 从环境变量获取租户ID
- tenantID := os.Getenv("INIT_TEST_TENANT_ID")
- logger.Infof(ctx, "Test tenant ID from environment: %s", tenantID)
-
- // 解析租户ID
- tenantIDUint, err := strconv.ParseUint(tenantID, 10, 64)
- if err != nil {
- // 解析失败时使用默认值0
- logger.Warn(ctx, "Failed to parse tenant ID, using default value 0")
- tenantIDUint = 0
- } else {
- // 初始化租户
- logger.Info(ctx, "Initializing tenant")
- err = s.initTenant(ctx)
- if err != nil {
- logger.Errorf(ctx, "Failed to initialize tenant: %v", err)
- return err
- }
- logger.Info(ctx, "Tenant initialized successfully")
- }
-
- // 创建带有租户ID的新上下文
- newCtx := context.Background()
- newCtx = context.WithValue(newCtx, types.TenantIDContextKey, uint(tenantIDUint))
- logger.Infof(ctx, "Created new context with tenant ID: %d", tenantIDUint)
-
- // 初始化模型
- modelInitFuncs := []struct {
- name string
- fn func(context.Context) error
- }{
- {"embedding model", s.initEmbeddingModel},
- {"rerank model", s.initRerankModel},
- {"LLM model", s.initLLMModel},
- }
-
- for _, initFunc := range modelInitFuncs {
- logger.Infof(ctx, "Initializing %s", initFunc.name)
- if err := initFunc.fn(newCtx); err != nil {
- logger.Errorf(ctx, "Failed to initialize %s: %v", initFunc.name, err)
- return err
- }
- logger.Infof(ctx, "%s initialized successfully", initFunc.name)
- }
-
- // 初始化知识库
- logger.Info(ctx, "Initializing knowledge base")
- if err := s.initKnowledgeBase(newCtx); err != nil {
- logger.Errorf(ctx, "Failed to initialize knowledge base: %v", err)
- return err
- }
- logger.Info(ctx, "Knowledge base initialized successfully")
-
- logger.Info(ctx, "Test data initialization completed")
- return nil
-}
-
-// getEnvOrError 获取环境变量值,如果不存在则返回错误
-func (s *TestDataService) getEnvOrError(name string) (string, error) {
- value := os.Getenv(name)
- if value == "" {
- return "", fmt.Errorf("%s environment variable is not set", name)
- }
- return value, nil
-}
-
-// updateOrCreateModel 更新或创建模型
-func (s *TestDataService) updateOrCreateModel(ctx context.Context, modelConfig *types.Model) error {
- model, err := s.modelService.GetModelByID(ctx, modelConfig.ID)
- if err != nil {
- // 模型不存在,创建新模型
- return s.modelService.CreateModel(ctx, modelConfig)
- }
-
- // 模型存在,更新属性
- model.TenantID = modelConfig.TenantID
- model.Name = modelConfig.Name
- model.Source = modelConfig.Source
- model.Type = modelConfig.Type
- model.Parameters = modelConfig.Parameters
- model.Status = modelConfig.Status
-
- return s.modelService.UpdateModel(ctx, model)
-}
-
-// initEmbeddingModel 初始化嵌入模型
-func (s *TestDataService) initEmbeddingModel(ctx context.Context) error {
- // 从环境变量获取模型参数
- modelName, err := s.getEnvOrError("INIT_EMBEDDING_MODEL_NAME")
- if err != nil {
- return err
- }
-
- dimensionStr := os.Getenv("INIT_EMBEDDING_MODEL_DIMENSION")
- dimension, err := strconv.Atoi(dimensionStr)
- if err != nil || dimension == 0 {
- return fmt.Errorf("invalid embedding model dimension: %s", dimensionStr)
- }
-
- baseURL := os.Getenv("INIT_EMBEDDING_MODEL_BASE_URL")
- apiKey := os.Getenv("INIT_EMBEDDING_MODEL_API_KEY")
-
- // 确定模型来源
- source := types.ModelSourceRemote
- if baseURL == "" {
- source = types.ModelSourceLocal
- }
-
- // 确定模型ID
- modelID := os.Getenv("INIT_EMBEDDING_MODEL_ID")
- if modelID == "" {
- modelID = fmt.Sprintf("builtin:%s:%d", modelName, dimension)
- }
-
- // 创建嵌入模型实例
- s.EmbedModel, err = embedding.NewEmbedder(embedding.Config{
- Source: source,
- BaseURL: baseURL,
- ModelName: modelName,
- APIKey: apiKey,
- Dimensions: dimension,
- ModelID: modelID,
- })
- if err != nil {
- return fmt.Errorf("failed to create embedder: %w", err)
- }
-
- // 如果是本地模型,使用Ollama拉取模型
- if source == types.ModelSourceLocal && s.ollamaService != nil {
- if err := s.ollamaService.PullModel(context.Background(), modelName); err != nil {
- return fmt.Errorf("failed to pull embedding model: %w", err)
- }
- }
-
- // 创建模型配置
- modelConfig := &types.Model{
- ID: modelID,
- TenantID: ctx.Value(types.TenantIDContextKey).(uint),
- Name: modelName,
- Source: source,
- Type: types.ModelTypeEmbedding,
- Parameters: types.ModelParameters{
- BaseURL: baseURL,
- APIKey: apiKey,
- EmbeddingParameters: types.EmbeddingParameters{
- Dimension: dimension,
- },
- },
- Status: "active",
- }
-
- // 更新或创建模型
- return s.updateOrCreateModel(ctx, modelConfig)
-}
-
-// initRerankModel 初始化重排模型
-func (s *TestDataService) initRerankModel(ctx context.Context) error {
- // 从环境变量获取模型参数
- modelName, err := s.getEnvOrError("INIT_RERANK_MODEL_NAME")
- if err != nil {
- logger.Warnf(ctx, "Skip Rerank Model: %v", err)
- return nil
- }
-
- baseURL, err := s.getEnvOrError("INIT_RERANK_MODEL_BASE_URL")
- if err != nil {
- return err
- }
-
- apiKey := os.Getenv("INIT_RERANK_MODEL_API_KEY")
- modelID := fmt.Sprintf("builtin:%s:rerank:%s", types.ModelSourceRemote, modelName)
-
- // 创建重排模型实例
- s.RerankModel, err = rerank.NewReranker(&rerank.RerankerConfig{
- Source: types.ModelSourceRemote,
- BaseURL: baseURL,
- ModelName: modelName,
- APIKey: apiKey,
- ModelID: modelID,
- })
- if err != nil {
- return fmt.Errorf("failed to create reranker: %w", err)
- }
-
- // 创建模型配置
- modelConfig := &types.Model{
- ID: modelID,
- TenantID: ctx.Value(types.TenantIDContextKey).(uint),
- Name: modelName,
- Source: types.ModelSourceRemote,
- Type: types.ModelTypeRerank,
- Parameters: types.ModelParameters{
- BaseURL: baseURL,
- APIKey: apiKey,
- },
- Status: "active",
- }
-
- // 更新或创建模型
- return s.updateOrCreateModel(ctx, modelConfig)
-}
-
-// initLLMModel 初始化大语言模型
-func (s *TestDataService) initLLMModel(ctx context.Context) error {
- // 从环境变量获取模型参数
- modelName, err := s.getEnvOrError("INIT_LLM_MODEL_NAME")
- if err != nil {
- return err
- }
-
- baseURL := os.Getenv("INIT_LLM_MODEL_BASE_URL")
- apiKey := os.Getenv("INIT_LLM_MODEL_API_KEY")
-
- // 确定模型来源
- source := types.ModelSourceRemote
- if baseURL == "" {
- source = types.ModelSourceLocal
- }
-
- // 确定模型ID
- modelID := fmt.Sprintf("builtin:%s:llm:%s", source, modelName)
-
- // 创建大语言模型实例
- s.LLMModel, err = chat.NewChat(&chat.ChatConfig{
- Source: source,
- BaseURL: baseURL,
- ModelName: modelName,
- APIKey: apiKey,
- ModelID: modelID,
- })
- if err != nil {
- return fmt.Errorf("failed to create llm: %w", err)
- }
-
- // 如果是本地模型,使用Ollama拉取模型
- if source == types.ModelSourceLocal && s.ollamaService != nil {
- if err := s.ollamaService.PullModel(context.Background(), modelName); err != nil {
- return fmt.Errorf("failed to pull llm model: %w", err)
- }
- }
-
- // 创建模型配置
- modelConfig := &types.Model{
- ID: modelID,
- TenantID: ctx.Value(types.TenantIDContextKey).(uint),
- Name: modelName,
- Source: source,
- Type: types.ModelTypeKnowledgeQA,
- Parameters: types.ModelParameters{
- BaseURL: baseURL,
- APIKey: apiKey,
- },
- Status: "active",
- }
-
- // 更新或创建模型
- return s.updateOrCreateModel(ctx, modelConfig)
-}
diff --git a/internal/container/container.go b/internal/container/container.go
index 795330f02..3a47bf365 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -89,7 +89,6 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(service.NewMessageService))
must(container.Provide(service.NewChunkService))
must(container.Provide(embedding.NewBatchEmbedder))
- must(container.Provide(service.NewTestDataService))
must(container.Provide(service.NewModelService))
must(container.Provide(service.NewDatasetService))
must(container.Provide(service.NewEvaluationService))
@@ -116,11 +115,11 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(handler.NewChunkHandler))
must(container.Provide(handler.NewSessionHandler))
must(container.Provide(handler.NewMessageHandler))
- must(container.Provide(handler.NewTestDataHandler))
must(container.Provide(handler.NewModelHandler))
must(container.Provide(handler.NewEvaluationHandler))
must(container.Provide(handler.NewInitializationHandler))
must(container.Provide(handler.NewAuthHandler))
+ must(container.Provide(handler.NewSystemHandler))
// Router configuration
must(container.Provide(router.NewRouter))
diff --git a/internal/handler/initialization.go b/internal/handler/initialization.go
index b74fd5580..e02003096 100644
--- a/internal/handler/initialization.go
+++ b/internal/handler/initialization.go
@@ -130,84 +130,40 @@ type InitializationRequest struct {
DocumentSplitting struct {
ChunkSize int `json:"chunkSize" binding:"required,min=100,max=10000"`
- ChunkOverlap int `json:"chunkOverlap" binding:"required,min=0"`
+ ChunkOverlap int `json:"chunkOverlap" binding:"min=0"`
Separators []string `json:"separators" binding:"required,min=1"`
} `json:"documentSplitting" binding:"required"`
}
-// CheckStatus 检查系统初始化状态
-func (h *InitializationHandler) CheckStatus(c *gin.Context) {
+// InitializeByKB 根据知识库ID执行配置更新
+func (h *InitializationHandler) InitializeByKB(c *gin.Context) {
ctx := c.Request.Context()
- logger.Info(ctx, "Checking system initialization status")
+ kbIdStr := c.Param("kbId")
- tenantID := ctx.Value(types.TenantIDContextKey).(uint)
+ logger.Infof(ctx, "Starting knowledge base configuration update, kbId: %s", kbIdStr)
- // 检查是否存在租户
- tenant, err := h.tenantService.GetTenantByID(ctx, tenantID)
- if err != nil {
- logger.ErrorWithFields(ctx, err, nil)
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{
- "initialized": false,
- },
- })
- return
- }
-
- // 如果没有租户,说明系统未初始化
- if tenant == nil {
- logger.Info(ctx, "No tenants found, system not initialized")
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{
- "initialized": false,
- },
- })
+ var req InitializationRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ logger.Error(ctx, "Failed to parse initialization request", err)
+ c.Error(errors.NewBadRequestError(err.Error()))
return
}
- // 检查是否存在模型
- models, err := h.modelService.ListModels(ctx)
- if err != nil || len(models) == 0 {
- logger.Info(ctx, "No models found, system not initialized")
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{
- "initialized": false,
- },
- })
+ // 获取指定知识库信息
+ kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbIdStr)
+ if err != nil {
+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"kbId": kbIdStr})
+ c.Error(errors.NewInternalServerError("获取知识库信息失败: " + err.Error()))
return
}
- // ignore api key in response for security
- for _, model := range models {
- model.Parameters.APIKey = ""
- }
-
- logger.Info(ctx, "System is already initialized")
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{
- "initialized": true,
- },
- })
-}
-// Initialize 执行系统初始化
-func (h *InitializationHandler) Initialize(c *gin.Context) {
- ctx := c.Request.Context()
-
- logger.Info(ctx, "Starting system initialization")
- tenantID := ctx.Value(types.TenantIDContextKey).(uint)
-
- var req InitializationRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- logger.Error(ctx, "Failed to parse initialization request", err)
- c.Error(errors.NewBadRequestError(err.Error()))
+ if kb == nil {
+ logger.Error(ctx, "Knowledge base not found", "kbId", kbIdStr)
+ c.Error(errors.NewNotFoundError("知识库不存在"))
return
}
- // 验证多模态配置
+ // 验证多模态配置(如果启用)
if req.Multimodal.Enabled {
storageType := strings.ToLower(req.Multimodal.StorageType)
if req.Multimodal.VLM == nil {
@@ -246,47 +202,12 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
if req.Rerank.Enabled {
if req.Rerank.ModelName == "" || req.Rerank.BaseURL == "" {
logger.Error(ctx, "Rerank configuration incomplete")
- c.Error(errors.NewBadRequestError("启用Rerank时需要配置模型名称和Base URL"))
+ c.Error(errors.NewBadRequestError("Rerank配置不完整"))
return
}
}
- // 验证文档分割配置
- if req.DocumentSplitting.ChunkOverlap >= req.DocumentSplitting.ChunkSize {
- logger.Error(ctx, "Chunk overlap must be less than chunk size")
- c.Error(errors.NewBadRequestError("分块重叠大小必须小于分块大小"))
- return
- }
- if len(req.DocumentSplitting.Separators) == 0 {
- logger.Error(ctx, "Document separators cannot be empty")
- c.Error(errors.NewBadRequestError("文档分隔符不能为空"))
- return
- }
- var err error
- // 1. 处理租户 - 检查是否存在,不存在则创建
- tenant, _ := h.tenantService.GetTenantByID(ctx, tenantID)
- if tenant == nil {
- logger.Info(ctx, "Tenant not found, creating tenant")
- err = errors.NewInternalServerError("Failed to get tenant")
- c.Error(err)
- return
- }
-
- // 2. 处理模型 - 检查现有模型并更新或创建
- existingModels, err := h.modelService.ListModels(ctx)
- if err != nil {
- logger.ErrorWithFields(ctx, err, nil)
- // 如果获取失败,继续执行创建流程
- existingModels = []*types.Model{}
- }
-
- // 构建模型映射,按类型分组
- modelMap := make(map[types.ModelType]*types.Model)
- for _, model := range existingModels {
- modelMap[model.Type] = model
- }
-
- // 要处理的模型配置
+ // 处理模型创建/更新
modelsToProcess := []struct {
modelType types.ModelType
name string
@@ -349,40 +270,49 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
modelType: types.ModelTypeVLLM,
name: req.Multimodal.VLM.ModelName,
source: types.ModelSourceRemote,
- description: "Vision Language Model",
+ description: "VLM Model",
baseURL: req.Multimodal.VLM.BaseURL,
apiKey: req.Multimodal.VLM.APIKey,
})
}
- // 处理每个模型
+ // 处理模型
var processedModels []*types.Model
- for _, modelConfig := range modelsToProcess {
- existingModel, exists := modelMap[modelConfig.modelType]
+ for _, modelInfo := range modelsToProcess {
+ model := &types.Model{
+ Type: modelInfo.modelType,
+ Name: modelInfo.name,
+ Source: modelInfo.source,
+ Description: modelInfo.description,
+ Parameters: types.ModelParameters{
+ BaseURL: modelInfo.baseURL,
+ APIKey: modelInfo.apiKey,
+ },
+ IsDefault: false,
+ Status: types.ModelStatusActive,
+ }
- if exists {
- // 更新现有模型
- logger.Infof(ctx, "Updating existing model: %s (%s)",
- modelConfig.name, modelConfig.modelType,
- )
- existingModel.Name = modelConfig.name
- existingModel.Source = modelConfig.source
- existingModel.Description = modelConfig.description
- existingModel.Parameters = types.ModelParameters{
- BaseURL: modelConfig.baseURL,
- APIKey: modelConfig.apiKey,
- EmbeddingParameters: types.EmbeddingParameters{
- Dimension: modelConfig.dimension,
- },
+ if modelInfo.modelType == types.ModelTypeEmbedding {
+ model.Parameters.EmbeddingParameters = types.EmbeddingParameters{
+ Dimension: modelInfo.dimension,
}
- existingModel.IsDefault = true
- existingModel.Status = types.ModelStatusActive
+ }
+
+ // 检查模型是否已存在
+ existingModel, err := h.modelService.GetModelByID(ctx, model.ID)
+ if err == nil && existingModel != nil {
+ // 更新现有模型
+ existingModel.Name = model.Name
+ existingModel.Source = model.Source
+ existingModel.Description = model.Description
+ existingModel.Parameters = model.Parameters
+ existingModel.UpdatedAt = time.Now()
- err := h.modelService.UpdateModel(ctx, existingModel)
+ err = h.modelService.UpdateModel(ctx, existingModel)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
- "model_name": modelConfig.name,
- "model_type": modelConfig.modelType,
+ "model_id": model.ID,
+ "kb_id": kbIdStr,
})
c.Error(errors.NewInternalServerError("更新模型失败: " + err.Error()))
return
@@ -390,74 +320,20 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
processedModels = append(processedModels, existingModel)
} else {
// 创建新模型
- logger.Infof(ctx,
- "Creating new model: %s (%s)",
- modelConfig.name, modelConfig.modelType,
- )
- newModel := &types.Model{
- TenantID: tenantID,
- Name: modelConfig.name,
- Type: modelConfig.modelType,
- Source: modelConfig.source,
- Description: modelConfig.description,
- Parameters: types.ModelParameters{
- BaseURL: modelConfig.baseURL,
- APIKey: modelConfig.apiKey,
- EmbeddingParameters: types.EmbeddingParameters{
- Dimension: modelConfig.dimension,
- },
- },
- IsDefault: true,
- Status: types.ModelStatusActive,
- }
-
- err := h.modelService.CreateModel(ctx, newModel)
+ err = h.modelService.CreateModel(ctx, model)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
- "model_name": modelConfig.name,
- "model_type": modelConfig.modelType,
+ "model_id": model.ID,
+ "kb_id": kbIdStr,
})
c.Error(errors.NewInternalServerError("创建模型失败: " + err.Error()))
return
}
- processedModels = append(processedModels, newModel)
- }
- }
-
- // 删除不需要的VLM模型(如果多模态被禁用)
- if !req.Multimodal.Enabled {
- if existingVLM, exists := modelMap[types.ModelTypeVLLM]; exists {
- logger.Info(ctx, "Deleting VLM model as multimodal is disabled")
- err := h.modelService.DeleteModel(ctx, existingVLM.ID)
- if err != nil {
- logger.ErrorWithFields(ctx, err, map[string]interface{}{
- "model_id": existingVLM.ID,
- })
- // 记录错误但不阻止流程
- logger.Warn(ctx, "Failed to delete VLM model, but continuing")
- }
- }
- }
-
- // 删除不需要的Rerank模型(如果Rerank被禁用)
- if !req.Rerank.Enabled {
- if existingRerank, exists := modelMap[types.ModelTypeRerank]; exists {
- logger.Info(ctx, "Deleting Rerank model as rerank is disabled")
- err := h.modelService.DeleteModel(ctx, existingRerank.ID)
- if err != nil {
- logger.ErrorWithFields(ctx, err, map[string]interface{}{
- "model_id": existingRerank.ID,
- })
- // 记录错误但不阻止流程
- logger.Warn(ctx, "Failed to delete Rerank model, but continuing")
- }
+ processedModels = append(processedModels, model)
}
}
- // 3. 处理知识库 - 检查是否存在,不存在则创建,存在则更新
- kbs, err := h.kbService.ListKnowledgeBases(ctx)
-
- // 找到embedding模型ID和LLM模型ID
+ // 找到模型ID
var embeddingModelID, llmModelID, rerankModelID, vlmModelID string
for _, model := range processedModels {
if model.Type == types.ModelTypeEmbedding {
@@ -466,7 +342,7 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
if model.Type == types.ModelTypeKnowledgeQA {
llmModelID = model.ID
}
- if model.Type == types.ModelTypeRerank && req.Rerank.Enabled {
+ if model.Type == types.ModelTypeRerank {
rerankModelID = model.ID
}
if model.Type == types.ModelTypeVLLM {
@@ -474,32 +350,31 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
}
}
- var kb *types.KnowledgeBase
-
- if len(kbs) == 0 {
- // 创建新知识库
- logger.Info(ctx, "Creating default knowledge base")
- kb = &types.KnowledgeBase{
- ID: uuid.New().String(),
- Name: "Default Knowledge Base",
- Description: "System Default Knowledge Base",
- TenantID: tenantID,
- ChunkingConfig: types.ChunkingConfig{
- ChunkSize: req.DocumentSplitting.ChunkSize,
- ChunkOverlap: req.DocumentSplitting.ChunkOverlap,
- Separators: req.DocumentSplitting.Separators,
- EnableMultimodal: req.Multimodal.Enabled,
- },
- EmbeddingModelID: embeddingModelID,
- SummaryModelID: llmModelID,
- RerankModelID: rerankModelID,
- VLMModelID: vlmModelID,
- VLMConfig: types.VLMConfig{
- ModelName: req.Multimodal.VLM.ModelName,
- BaseURL: req.Multimodal.VLM.BaseURL,
- APIKey: req.Multimodal.VLM.APIKey,
- InterfaceType: req.Multimodal.VLM.InterfaceType,
- },
+ // 更新知识库配置
+ kb.SummaryModelID = llmModelID
+ kb.EmbeddingModelID = embeddingModelID
+ if req.Rerank.Enabled {
+ kb.RerankModelID = rerankModelID
+ } else {
+ kb.RerankModelID = ""
+ }
+
+ // 更新文档分割配置
+ kb.ChunkingConfig = types.ChunkingConfig{
+ ChunkSize: req.DocumentSplitting.ChunkSize,
+ ChunkOverlap: req.DocumentSplitting.ChunkOverlap,
+ Separators: req.DocumentSplitting.Separators,
+ }
+
+ // 更新多模态配置
+ if req.Multimodal.Enabled {
+ kb.ChunkingConfig.EnableMultimodal = true
+ kb.VLMModelID = vlmModelID
+ kb.VLMConfig = types.VLMConfig{
+ ModelName: req.Multimodal.VLM.ModelName,
+ BaseURL: req.Multimodal.VLM.BaseURL,
+ APIKey: req.Multimodal.VLM.APIKey,
+ InterfaceType: req.Multimodal.VLM.InterfaceType,
}
switch req.Multimodal.StorageType {
case "cos":
@@ -525,124 +400,24 @@ func (h *InitializationHandler) Initialize(c *gin.Context) {
}
}
}
-
- _, err = h.kbService.CreateKnowledgeBase(ctx, kb)
- if err != nil {
- logger.ErrorWithFields(ctx, err, nil)
- c.Error(errors.NewInternalServerError("创建知识库失败: " + err.Error()))
- return
- }
} else {
- // 更新现有知识库
- logger.Info(ctx, "Updating existing knowledge base")
- kb = kbs[0]
-
- // 检查是否有文件,如果有文件则不允许修改Embedding模型
- knowledgeList, err := h.knowledgeService.ListKnowledgeByKnowledgeBaseID(
- ctx, kb.ID,
- )
- hasFiles := err == nil && len(knowledgeList) > 0
-
- // 先更新模型ID(直接在对象上)
- kb.SummaryModelID = llmModelID
- if req.Rerank.Enabled {
- kb.RerankModelID = rerankModelID
- } else {
- kb.RerankModelID = "" // 清空Rerank模型ID
- }
- if req.Multimodal.Enabled {
- kb.VLMModelID = vlmModelID
- // 更新VLM配置
- kb.VLMConfig = types.VLMConfig{
- ModelName: req.Multimodal.VLM.ModelName,
- BaseURL: req.Multimodal.VLM.BaseURL,
- APIKey: req.Multimodal.VLM.APIKey,
- InterfaceType: req.Multimodal.VLM.InterfaceType,
- }
- switch req.Multimodal.StorageType {
- case "cos":
- if req.Multimodal.COS != nil {
- kb.StorageConfig = types.StorageConfig{
- Provider: req.Multimodal.StorageType,
- SecretID: req.Multimodal.COS.SecretID,
- SecretKey: req.Multimodal.COS.SecretKey,
- Region: req.Multimodal.COS.Region,
- BucketName: req.Multimodal.COS.BucketName,
- AppID: req.Multimodal.COS.AppID,
- PathPrefix: req.Multimodal.COS.PathPrefix,
- }
- }
- case "minio":
- if req.Multimodal.Minio != nil {
- kb.StorageConfig = types.StorageConfig{
- Provider: req.Multimodal.StorageType,
- BucketName: req.Multimodal.Minio.BucketName,
- PathPrefix: req.Multimodal.Minio.PathPrefix,
- SecretID: os.Getenv("MINIO_ACCESS_KEY_ID"),
- SecretKey: os.Getenv("MINIO_SECRET_ACCESS_KEY"),
- }
- }
- }
- } else {
- kb.VLMModelID = "" // 清空VLM模型ID
- // 清空VLM配置
- kb.VLMConfig = types.VLMConfig{}
- kb.StorageConfig = types.StorageConfig{}
- }
- if !hasFiles {
- kb.EmbeddingModelID = embeddingModelID
- }
- kb.ChunkingConfig = types.ChunkingConfig{
- ChunkSize: req.DocumentSplitting.ChunkSize,
- ChunkOverlap: req.DocumentSplitting.ChunkOverlap,
- Separators: req.DocumentSplitting.Separators,
- EnableMultimodal: req.Multimodal.Enabled,
- }
-
- // 更新基本信息和配置
- err = h.kbRepository.UpdateKnowledgeBase(ctx, kb)
- if err != nil {
- logger.ErrorWithFields(ctx, err, nil)
- c.Error(errors.NewInternalServerError("更新知识库配置失败: " + err.Error()))
- return
- }
-
- // 如果需要更新模型ID,使用repository直接更新
- if !hasFiles || kb.SummaryModelID != llmModelID {
- // 刷新知识库对象以获取最新信息
- kb, err = h.kbService.GetKnowledgeBaseByID(ctx, kb.ID)
- if err != nil {
- logger.ErrorWithFields(ctx, err, nil)
- c.Error(errors.NewInternalServerError("获取更新后的知识库失败: " + err.Error()))
- return
- }
-
- // 更新模型ID
- kb.SummaryModelID = llmModelID
- if req.Rerank.Enabled {
- kb.RerankModelID = rerankModelID
- } else {
- kb.RerankModelID = "" // 清空Rerank模型ID
- }
-
- // 使用repository直接更新模型ID
- err = h.kbRepository.UpdateKnowledgeBase(ctx, kb)
- if err != nil {
- logger.ErrorWithFields(ctx, err, nil)
- c.Error(errors.NewInternalServerError("更新知识库模型ID失败: " + err.Error()))
- return
- }
+ kb.VLMModelID = ""
+ kb.VLMConfig = types.VLMConfig{}
+ kb.StorageConfig = types.StorageConfig{}
+ }
- logger.Info(ctx, "Model IDs updated successfully")
- }
+ err = h.kbRepository.UpdateKnowledgeBase(ctx, kb)
+ if err != nil {
+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"kbId": kbIdStr})
+ c.Error(errors.NewInternalServerError("更新知识库配置失败: " + err.Error()))
+ return
}
- logger.Info(ctx, "System initialization completed successfully")
+ logger.Info(ctx, "Knowledge base configuration updated successfully", "kbId", kbIdStr)
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "系统初始化成功",
+ "message": "知识库配置更新成功",
"data": gin.H{
- "tenant": tenant,
"models": processedModels,
"knowledge_base": kb,
},
@@ -1029,39 +804,53 @@ func (h *InitializationHandler) updateTaskStatus(
}
}
-// GetCurrentConfig 获取当前系统配置信息
-func (h *InitializationHandler) GetCurrentConfig(c *gin.Context) {
+// GetCurrentConfigByKB 根据知识库ID获取配置信息
+func (h *InitializationHandler) GetCurrentConfigByKB(c *gin.Context) {
ctx := c.Request.Context()
+ kbIdStr := c.Param("kbId")
- logger.Info(ctx, "Getting current system configuration")
+ logger.Info(ctx, "Getting configuration for knowledge base", "kbId", kbIdStr)
- // 获取模型信息
- models, err := h.modelService.ListModels(ctx)
+ // 获取指定知识库信息
+ kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbIdStr)
if err != nil {
- logger.ErrorWithFields(ctx, err, nil)
- c.Error(errors.NewInternalServerError("获取模型列表失败: " + err.Error()))
+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"kbId": kbIdStr})
+ c.Error(errors.NewInternalServerError("获取知识库信息失败: " + err.Error()))
return
}
- // 获取知识库信息
- kbs, err := h.kbService.ListKnowledgeBases(ctx)
- if err != nil {
- logger.ErrorWithFields(ctx, err, nil)
- c.Error(errors.NewInternalServerError("获取知识库信息失败: " + err.Error()))
+ if kb == nil {
+ logger.Error(ctx, "Knowledge base not found", "kbId", kbIdStr)
+ c.Error(errors.NewNotFoundError("知识库不存在"))
return
}
- if len(kbs) == 0 {
- logger.Error(ctx, "No knowledge bases found")
- c.Error(errors.NewInternalServerError("获取知识库信息失败"))
- return
+ // 根据知识库的模型ID获取特定模型
+ var models []*types.Model
+ modelIDs := []string{
+ kb.EmbeddingModelID,
+ kb.SummaryModelID,
+ kb.RerankModelID,
+ kb.VLMModelID,
}
- kb := kbs[0]
+ for _, modelID := range modelIDs {
+ if modelID != "" {
+ model, err := h.modelService.GetModelByID(ctx, modelID)
+ if err != nil {
+ logger.Warn(ctx, "Failed to get model", "kbId", kbIdStr, "modelId", modelID, "error", err)
+ // 如果模型不存在或获取失败,继续处理其他模型
+ continue
+ }
+ if model != nil {
+ models = append(models, model)
+ }
+ }
+ }
// 检查知识库是否有文件
knowledgeList, err := h.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx,
- kb.ID, &types.Pagination{
+ kbIdStr, &types.Pagination{
Page: 1,
PageSize: 1,
})
@@ -1073,7 +862,7 @@ func (h *InitializationHandler) GetCurrentConfig(c *gin.Context) {
// 构建配置响应
config := buildConfigResponse(models, kb, hasFiles)
- logger.Info(ctx, "Current system configuration retrieved successfully")
+ logger.Info(ctx, "Knowledge base configuration retrieved successfully", "kbId", kbIdStr)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": config,
diff --git a/internal/handler/session.go b/internal/handler/session.go
index 1f4361565..870a024e0 100644
--- a/internal/handler/session.go
+++ b/internal/handler/session.go
@@ -7,7 +7,6 @@ import (
"net/http"
"time"
- "github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
@@ -22,7 +21,6 @@ type SessionHandler struct {
sessionService interfaces.SessionService // Service for managing sessions
streamManager interfaces.StreamManager // Manager for handling streaming responses
config *config.Config // Application configuration
- testDataService *service.TestDataService // Service for test data (models, etc.)
knowledgebaseService interfaces.KnowledgeBaseService
}
@@ -32,7 +30,6 @@ func NewSessionHandler(
messageService interfaces.MessageService,
streamManager interfaces.StreamManager,
config *config.Config,
- testDataService *service.TestDataService,
knowledgebaseService interfaces.KnowledgeBaseService,
) *SessionHandler {
return &SessionHandler{
@@ -40,7 +37,6 @@ func NewSessionHandler(
messageService: messageService,
streamManager: streamManager,
config: config,
- testDataService: testDataService,
knowledgebaseService: knowledgebaseService,
}
}
diff --git a/internal/handler/system.go b/internal/handler/system.go
new file mode 100644
index 000000000..43329d957
--- /dev/null
+++ b/internal/handler/system.go
@@ -0,0 +1,49 @@
+package handler
+
+import (
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/gin-gonic/gin"
+)
+
+// SystemHandler handles system-related requests
+type SystemHandler struct{}
+
+// NewSystemHandler creates a new system handler
+func NewSystemHandler() *SystemHandler {
+ return &SystemHandler{}
+}
+
+// GetSystemInfoResponse defines the response structure for system info
+type GetSystemInfoResponse struct {
+ Version string `json:"version"`
+ CommitID string `json:"commit_id,omitempty"`
+ BuildTime string `json:"build_time,omitempty"`
+ GoVersion string `json:"go_version,omitempty"`
+}
+
+// 编译时注入的版本信息
+var (
+ Version = "unknown"
+ CommitID = "unknown"
+ BuildTime = "unknown"
+ GoVersion = "unknown"
+)
+
+// GetSystemInfo gets system information including version and commit ID
+func (h *SystemHandler) GetSystemInfo(c *gin.Context) {
+ ctx := logger.CloneContext(c.Request.Context())
+
+ response := GetSystemInfoResponse{
+ Version: Version,
+ CommitID: CommitID,
+ BuildTime: BuildTime,
+ GoVersion: GoVersion,
+ }
+
+ logger.Info(ctx, "System info retrieved successfully")
+ c.JSON(200, gin.H{
+ "code": 0,
+ "msg": "success",
+ "data": response,
+ })
+}
diff --git a/internal/handler/test_data.go b/internal/handler/test_data.go
deleted file mode 100644
index 0b5a57ffd..000000000
--- a/internal/handler/test_data.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package handler
-
-import (
- "net/http"
-
- "github.com/gin-gonic/gin"
-
- "github.com/Tencent/WeKnora/internal/config"
- "github.com/Tencent/WeKnora/internal/errors"
- "github.com/Tencent/WeKnora/internal/logger"
- "github.com/Tencent/WeKnora/internal/types"
- "github.com/Tencent/WeKnora/internal/types/interfaces"
-)
-
-// TestDataHandler handles HTTP requests related to test data operations
-// Used for development and testing purposes to provide sample data
-type TestDataHandler struct {
- config *config.Config
- kbService interfaces.KnowledgeBaseService
- tenantService interfaces.TenantService
-}
-
-// NewTestDataHandler creates a new instance of the test data handler
-// Parameters:
-// - config: Application configuration instance
-// - kbService: Knowledge base service for accessing knowledge base data
-// - tenantService: Tenant service for accessing tenant data
-//
-// Returns a pointer to the new TestDataHandler instance
-func NewTestDataHandler(
- config *config.Config,
- kbService interfaces.KnowledgeBaseService,
- tenantService interfaces.TenantService,
-) *TestDataHandler {
- return &TestDataHandler{
- config: config,
- kbService: kbService,
- tenantService: tenantService,
- }
-}
-
-// GetTestData handles the HTTP request to retrieve test data for development purposes
-// It returns predefined test tenant and knowledge base information
-// This endpoint is only available in non-production environments
-// Parameters:
-// - c: Gin context for the HTTP request
-func (h *TestDataHandler) GetTestData(c *gin.Context) {
- ctx := c.Request.Context()
-
- logger.Info(ctx, "Start retrieving test data")
-
- tenantID := c.GetUint(types.TenantIDContextKey.String())
- logger.Debugf(ctx, "Test tenant ID environment variable: %d", tenantID)
-
- // Retrieve the test tenant data
- logger.Infof(ctx, "Retrieving test tenant, ID: %d", tenantID)
- tenant, err := h.tenantService.GetTenantByID(ctx, tenantID)
- if err != nil {
- logger.ErrorWithFields(ctx, err, nil)
- c.Error(err)
- return
- }
-
- // Retrieve the test knowledge base data
- kbs, err := h.kbService.ListKnowledgeBases(ctx)
- if err != nil {
- logger.ErrorWithFields(ctx, err, nil)
- c.Error(err)
- return
- }
-
- if len(kbs) == 0 {
- logger.Error(ctx, "No knowledge bases found")
- c.Error(errors.NewInternalServerError("获取知识库信息失败"))
- return
- }
-
- logger.Info(ctx, "Test data retrieved successfully")
- // Return the test data in the response
- c.JSON(http.StatusOK, gin.H{
- "data": gin.H{
- "tenant": tenant,
- "knowledge_bases": kbs,
- },
- "success": true,
- })
-}
diff --git a/internal/models/chat/remote_api.go b/internal/models/chat/remote_api.go
index b10396916..283dc14b5 100644
--- a/internal/models/chat/remote_api.go
+++ b/internal/models/chat/remote_api.go
@@ -85,6 +85,7 @@ func (c *RemoteAPIChat) buildChatCompletionRequest(messages []Message,
Messages: c.convertMessages(messages),
Stream: isStream,
}
+ thinking := false
// 添加可选参数
if opts != nil {
@@ -106,6 +107,13 @@ func (c *RemoteAPIChat) buildChatCompletionRequest(messages []Message,
if opts.PresencePenalty > 0 {
req.PresencePenalty = float32(opts.PresencePenalty)
}
+ if opts.Thinking != nil {
+ thinking = *opts.Thinking
+ }
+ }
+
+ req.ChatTemplateKwargs = map[string]interface{}{
+ "enable_thinking": thinking,
}
return req
diff --git a/internal/router/router.go b/internal/router/router.go
index 6d1abcd32..9d2354244 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -33,11 +33,11 @@ type RouterParams struct {
ChunkHandler *handler.ChunkHandler
SessionHandler *handler.SessionHandler
MessageHandler *handler.MessageHandler
- TestDataHandler *handler.TestDataHandler
ModelHandler *handler.ModelHandler
EvaluationHandler *handler.EvaluationHandler
AuthHandler *handler.AuthHandler
InitializationHandler *handler.InitializationHandler
+ SystemHandler *handler.SystemHandler
}
// NewRouter 创建新的路由
@@ -83,7 +83,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterModelRoutes(v1, params.ModelHandler)
RegisterEvaluationRoutes(v1, params.EvaluationHandler)
RegisterInitializationRoutes(v1, params.InitializationHandler)
- RegisterTestDataRoutes(v1, params.TestDataHandler)
+ RegisterSystemRoutes(v1, params.SystemHandler)
}
return r
@@ -238,10 +238,6 @@ func RegisterEvaluationRoutes(r *gin.RouterGroup, handler *handler.EvaluationHan
}
}
-func RegisterTestDataRoutes(r *gin.RouterGroup, handler *handler.TestDataHandler) {
- r.GET("/test-data", handler.GetTestData)
-}
-
// RegisterAuthRoutes registers authentication routes
func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
r.POST("/auth/register", handler.Register)
@@ -255,9 +251,8 @@ func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.InitializationHandler) {
// 初始化接口
- r.GET("/initialization/status", handler.CheckStatus)
- r.GET("/initialization/config", handler.GetCurrentConfig)
- r.POST("/initialization/initialize", handler.Initialize)
+ r.GET("/initialization/config/:kbId", handler.GetCurrentConfigByKB)
+ r.POST("/initialization/initialize/:kbId", handler.InitializeByKB)
// Ollama相关接口
r.GET("/initialization/ollama/status", handler.CheckOllamaStatus)
@@ -273,3 +268,11 @@ func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.Initializ
r.POST("/initialization/rerank/check", handler.CheckRerankModel)
r.POST("/initialization/multimodal/test", handler.TestMultimodalFunction)
}
+
+// RegisterSystemRoutes registers system information routes
+func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler) {
+ systemRoutes := r.Group("/system")
+ {
+ systemRoutes.GET("/info", handler.GetSystemInfo)
+ }
+}
diff --git a/scripts/build_images.sh b/scripts/build_images.sh
index 8bbcc430b..0767d8543 100755
--- a/scripts/build_images.sh
+++ b/scripts/build_images.sh
@@ -91,17 +91,56 @@ check_platform() {
log_info "当前架构:$TARGETARCH"
}
+# 获取版本信息
+get_version_info() {
+ # 从VERSION文件获取版本号
+ if [ -f "VERSION" ]; then
+ VERSION=$(cat VERSION | tr -d '\n\r')
+ else
+ VERSION="unknown"
+ fi
+
+ # 获取commit ID
+ if command -v git >/dev/null 2>&1; then
+ COMMIT_ID=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
+ else
+ COMMIT_ID="unknown"
+ fi
+
+ # 获取构建时间
+ BUILD_TIME=$(date -u '+%Y-%m-%d %H:%M:%S UTC')
+
+ # 获取Go版本
+ if command -v go >/dev/null 2>&1; then
+ GO_VERSION=$(go version 2>/dev/null || echo "unknown")
+ else
+ GO_VERSION="unknown"
+ fi
+
+ log_info "版本信息: $VERSION"
+ log_info "Commit ID: $COMMIT_ID"
+ log_info "构建时间: $BUILD_TIME"
+ log_info "Go版本: $GO_VERSION"
+}
+
# 构建应用镜像
build_app_image() {
log_info "构建应用镜像 (weknora-app)..."
cd "$PROJECT_ROOT"
+ # 获取版本信息
+ get_version_info
+
docker build \
--platform $PLATFORM \
--build-arg GOPRIVATE_ARG=${GOPRIVATE:-""} \
--build-arg GOPROXY_ARG=${GOPROXY:-"https://goproxy.cn,direct"} \
--build-arg GOSUMDB_ARG=${GOSUMDB:-"off"} \
+ --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 wechatopenai/weknora-app:latest \
.
diff --git a/scripts/get_version.sh b/scripts/get_version.sh
new file mode 100755
index 000000000..af781b4d4
--- /dev/null
+++ b/scripts/get_version.sh
@@ -0,0 +1,86 @@
+#!/bin/bash
+# 统一的版本信息获取脚本
+# 支持本地构建和CI构建环境
+
+# 设置默认值
+VERSION="unknown"
+COMMIT_ID="unknown"
+BUILD_TIME="unknown"
+GO_VERSION="unknown"
+
+# 获取版本号
+if [ -f "VERSION" ]; then
+ VERSION=$(cat VERSION | tr -d '\n\r')
+fi
+
+# 获取commit ID
+if [ -n "$GITHUB_SHA" ]; then
+ # GitHub Actions环境
+ COMMIT_ID="${GITHUB_SHA:0:7}"
+elif command -v git >/dev/null 2>&1; then
+ # 本地环境
+ COMMIT_ID=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
+fi
+
+# 获取构建时间
+if [ -n "$GITHUB_ACTIONS" ]; then
+ # GitHub Actions环境,使用标准时间格式
+ BUILD_TIME=$(date -u '+%Y-%m-%d %H:%M:%S UTC')
+else
+ # 本地环境
+ BUILD_TIME=$(date -u '+%Y-%m-%d %H:%M:%S UTC')
+fi
+
+# 获取Go版本
+if command -v go >/dev/null 2>&1; then
+ GO_VERSION=$(go version 2>/dev/null || echo "unknown")
+fi
+
+# 根据参数输出不同格式
+case "${1:-env}" in
+ "env")
+ # 输出环境变量格式
+ echo "VERSION=$VERSION"
+ echo "COMMIT_ID=$COMMIT_ID"
+ echo "BUILD_TIME=$BUILD_TIME"
+ echo "GO_VERSION=$GO_VERSION"
+ ;;
+ "json")
+ # 输出JSON格式
+ cat << EOF
+{
+ "version": "$VERSION",
+ "commit_id": "$COMMIT_ID",
+ "build_time": "$BUILD_TIME",
+ "go_version": "$GO_VERSION"
+}
+EOF
+ ;;
+ "docker-args")
+ # 输出Docker构建参数格式
+ echo "--build-arg VERSION_ARG=$VERSION"
+ echo "--build-arg COMMIT_ID_ARG=$COMMIT_ID"
+ echo "--build-arg BUILD_TIME_ARG=$BUILD_TIME"
+ echo "--build-arg GO_VERSION_ARG=$GO_VERSION"
+ ;;
+ "ldflags")
+ # 输出Go ldflags格式
+ echo "-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'"
+ ;;
+ "info")
+ # 输出信息格式
+ echo "版本信息: $VERSION"
+ echo "Commit ID: $COMMIT_ID"
+ echo "构建时间: $BUILD_TIME"
+ echo "Go版本: $GO_VERSION"
+ ;;
+ *)
+ echo "用法: $0 [env|json|docker-args|ldflags|info]"
+ echo " env - 输出环境变量格式 (默认)"
+ echo " json - 输出JSON格式"
+ echo " docker-args - 输出Docker构建参数格式"
+ echo " ldflags - 输出Go ldflags格式"
+ echo " info - 输出信息格式"
+ exit 1
+ ;;
+esac