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: Integrate vue-i18n for multilingual support across components

wizardchen59f3d2216942
diff --git a/.gitignore b/.gitignore
index 45726fbe6..037d0fd66 100644
--- a/.gitignore
+++ b/.gitignore
@@ -42,4 +42,5 @@ data/files/
# General
.DS_Store
/scripts/scale_dev_jobs.sh
-server
\ No newline at end of file
+server
+frontend/.vite
\ No newline at end of file
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index d654db37a..0df5164d0 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -19,6 +19,7 @@
"tdesign-icons-vue-next": "^0.4.1",
"tdesign-vue-next": "^1.17.2",
"vue": "^3.5.13",
+ "vue-i18n": "^11.1.12",
"vue-router": "^4.5.0",
"webpack": "^5.94.0"
},
@@ -871,6 +872,50 @@
"node": ">=18"
}
},
+ "node_modules/@intlify/core-base": {
+ "version": "11.1.12",
+ "resolved": "https://mirrors.tencent.com/npm/@intlify/core-base/-/core-base-11.1.12.tgz",
+ "integrity": "sha512-whh0trqRsSqVLNEUCwU59pyJZYpU8AmSWl8M3Jz2Mv5ESPP6kFh4juas2NpZ1iCvy7GlNRffUD1xr84gceimjg==",
+ "license": "MIT",
+ "dependencies": {
+ "@intlify/message-compiler": "11.1.12",
+ "@intlify/shared": "11.1.12"
+ },
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/kazupon"
+ }
+ },
+ "node_modules/@intlify/message-compiler": {
+ "version": "11.1.12",
+ "resolved": "https://mirrors.tencent.com/npm/@intlify/message-compiler/-/message-compiler-11.1.12.tgz",
+ "integrity": "sha512-Fv9iQSJoJaXl4ZGkOCN1LDM3trzze0AS2zRz2EHLiwenwL6t0Ki9KySYlyr27yVOj5aVz0e55JePO+kELIvfdQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@intlify/shared": "11.1.12",
+ "source-map-js": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/kazupon"
+ }
+ },
+ "node_modules/@intlify/shared": {
+ "version": "11.1.12",
+ "resolved": "https://mirrors.tencent.com/npm/@intlify/shared/-/shared-11.1.12.tgz",
+ "integrity": "sha512-Om86EjuQtA69hdNj3GQec9ZC0L0vPSAnXzB3gP/gyJ7+mA7t06d9aOAiqMZ+xEOsumGP4eEBlfl8zF2LOTzf2A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/kazupon"
+ }
+ },
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.12",
"resolved": "https://mirrors.tencent.com/npm/@jridgewell/gen-mapping/-/gen-mapping-0.3.12.tgz",
@@ -3711,6 +3756,31 @@
}
}
},
+ "node_modules/vue-i18n": {
+ "version": "11.1.12",
+ "resolved": "https://mirrors.tencent.com/npm/vue-i18n/-/vue-i18n-11.1.12.tgz",
+ "integrity": "sha512-BnstPj3KLHLrsqbVU2UOrPmr0+Mv11bsUZG0PyCOzsawCivk8W00GMXHeVUWIDOgNaScCuZah47CZFE+Wnl8mw==",
+ "dependencies": {
+ "@intlify/core-base": "11.1.12",
+ "@intlify/shared": "11.1.12",
+ "@vue/devtools-api": "^6.5.0"
+ },
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/kazupon"
+ },
+ "peerDependencies": {
+ "vue": "^3.0.0"
+ }
+ },
+ "node_modules/vue-i18n/node_modules/@vue/devtools-api": {
+ "version": "6.6.4",
+ "resolved": "https://mirrors.tencent.com/npm/@vue/devtools-api/-/devtools-api-6.6.4.tgz",
+ "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==",
+ "license": "MIT"
+ },
"node_modules/vue-router": {
"version": "4.5.1",
"resolved": "https://mirrors.tencent.com/npm/vue-router/-/vue-router-4.5.1.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index f4c7df64c..6ef658949 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -23,6 +23,7 @@
"tdesign-icons-vue-next": "^0.4.1",
"tdesign-vue-next": "^1.17.2",
"vue": "^3.5.13",
+ "vue-i18n": "^11.1.12",
"vue-router": "^4.5.0",
"webpack": "^5.94.0"
},
diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue
index 772468978..aae4f8d74 100644
--- a/frontend/src/components/Input-field.vue
+++ b/frontend/src/components/Input-field.vue
@@ -10,6 +10,7 @@ import { stopSession } from '@/api/chat';
import KnowledgeBaseSelector from './KnowledgeBaseSelector.vue';
import { getModel, type ModelConfig } from '@/api/model';
import { getTenantWebSearchConfig } from '@/api/web-search';
+import { useI18n } from 'vue-i18n';
const route = useRoute();
const router = useRouter();
@@ -56,6 +57,8 @@ const showModelSelector = ref(false);
const modelButtonRef = ref<HTMLElement>();
const modelDropdownStyle = ref<Record<string, string>>({});
+const { t } = useI18n();
+
// 显示的知识库标签(最多显示2个)
const displayedKbs = computed(() => selectedKbs.value.slice(0, 2));
const remainingCount = computed(() => Math.max(0, selectedKbs.value.length - 2));
@@ -299,15 +302,15 @@ const emit = defineEmits(['send-msg', 'stop-generation']);
const createSession = (val: string) => {
if (!val.trim()) {
- MessagePlugin.info("请先输入内容!");
+ MessagePlugin.info(t('input.messages.enterContent'));
return;
}
if (selectedKbIds.value.length === 0) {
- MessagePlugin.warning("请先选择知识库!");
+ MessagePlugin.warning(t('input.messages.selectKnowledge'));
return;
}
if (props.isReplying) {
- return MessagePlugin.error("正在回复中,请稍后再试!");
+ return MessagePlugin.error(t('input.messages.replying'));
}
emit('send-msg', val, selectedModelId.value);
clearvalue();
@@ -438,7 +441,7 @@ const selectAgentMode = (mode: 'normal' | 'agent') => {
const shouldEnableAgent = mode === 'agent';
if (shouldEnableAgent !== isAgentEnabled.value) {
settingsStore.toggleAgent(shouldEnableAgent);
- MessagePlugin.success(shouldEnableAgent ? '已切换到 Agent 模式' : '已切换到普通模式');
+ MessagePlugin.success(shouldEnableAgent ? t('input.messages.agentSwitchedOn') : t('input.messages.agentSwitchedOff'));
}
showAgentModeSelector.value = false;
}
@@ -482,7 +485,7 @@ const toggleAgentMode = () => {
if (!agentReady) {
// 创建带跳转链接的自定义消息
const messageContent = h('div', { style: 'display: flex; align-items: center; gap: 8px; flex-wrap: wrap;' }, [
- h('span', { style: 'flex: 1; min-width: 0;' }, 'Agent 未就绪,请先在设置中完成 Agent 配置(思考模型、Rerank 模型和允许的工具)'),
+ h('span', { style: 'flex: 1; min-width: 0;' }, t('input.messages.agentNotReadyDetail')),
h('a', {
href: '#',
onClick: (e: Event) => {
@@ -496,7 +499,7 @@ const toggleAgentMode = () => {
onMouseleave: (e: Event) => {
(e.target as HTMLElement).style.textDecoration = 'none';
}
- }, '去设置 →')
+ }, t('input.goToSettings'))
]);
MessagePlugin.warning({
@@ -509,14 +512,14 @@ const toggleAgentMode = () => {
// 正常切换 Agent 状态
settingsStore.toggleAgent(!isAgentEnabled.value);
- const message = isAgentEnabled.value ? 'Agent 模式已启用' : 'Agent 模式已禁用';
+ const message = isAgentEnabled.value ? t('input.messages.agentEnabled') : t('input.messages.agentDisabled');
MessagePlugin.success(message);
}
const toggleWebSearch = () => {
if (!isWebSearchConfigured.value) {
const messageContent = h('div', { style: 'display: flex; flex-direction: column; gap: 6px; max-width: 280px;' }, [
- h('span', { style: 'color: #333; line-height: 1.5;' }, '未配置网络搜索引擎,请先在设置中完成搜索引擎选择与接口配置。'),
+ h('span', { style: 'color: #333; line-height: 1.5;' }, t('input.messages.webSearchNotConfigured')),
h('a', {
href: '#',
onClick: (e: Event) => {
@@ -530,7 +533,7 @@ const toggleWebSearch = () => {
onMouseleave: (e: Event) => {
(e.target as HTMLElement).style.textDecoration = 'none';
}
- }, '去设置 →')
+ }, t('input.goToSettings'))
]);
MessagePlugin.warning({
content: () => messageContent,
@@ -542,7 +545,7 @@ const toggleWebSearch = () => {
const currentValue = settingsStore.isWebSearchEnabled;
const newValue = !currentValue;
settingsStore.toggleWebSearch(newValue);
- MessagePlugin.success(newValue ? '网络搜索已开启' : '网络搜索已关闭');
+ MessagePlugin.success(newValue ? t('input.messages.webSearchEnabled') : t('input.messages.webSearchDisabled'));
};
const toggleKbSelector = () => {
@@ -555,13 +558,13 @@ const removeKb = (kbId: string) => {
const handleStop = async () => {
if (!props.sessionId) {
- MessagePlugin.warning('会话 ID 不存在');
+ MessagePlugin.warning(t('input.messages.sessionMissing'));
return;
}
if (!props.assistantMessageId) {
console.error('[Stop] Assistant message ID is empty');
- MessagePlugin.warning('无法获取消息 ID,请刷新页面后重试');
+ MessagePlugin.warning(t('input.messages.messageMissing'));
return;
}
@@ -572,10 +575,10 @@ const handleStop = async () => {
try {
await stopSession(props.sessionId, props.assistantMessageId);
- MessagePlugin.success('已停止生成');
+ MessagePlugin.success(t('input.messages.stopSuccess'));
} catch (error) {
console.error('Failed to stop session:', error);
- MessagePlugin.error('停止失败,请重试');
+ MessagePlugin.error(t('input.messages.stopFailed'));
}
}
@@ -587,7 +590,7 @@ onBeforeRouteUpdate((to, from, next) => {
</script>
<template>
<div class="answers-input">
- <t-textarea v-model="query" placeholder="基于知识库提问" name="description" :autosize="true" @keydown="onKeydown" />
+ <t-textarea v-model="query" :placeholder="$t('input.placeholder')" name="description" :autosize="true" @keydown="onKeydown" />
<!-- 控制栏 -->
<div class="control-bar">
@@ -606,7 +609,7 @@ onBeforeRouteUpdate((to, from, next) => {
<img
v-if="isAgentEnabled"
:src="getImgSrc('agent-active.svg')"
- alt="Agent模式"
+ :alt="$t('input.agentMode')"
class="control-icon agent-icon"
/>
<svg
@@ -621,7 +624,7 @@ onBeforeRouteUpdate((to, from, next) => {
<path d="M8 4.5a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7zM6 8a2 2 0 1 1 4 0 2 2 0 0 1-4 0z"/>
</svg>
<span class="agent-mode-text">
- {{ isAgentEnabled ? 'Agent 模式' : '普通模式' }}
+ {{ isAgentEnabled ? $t('input.agentMode') : $t('input.normalMode') }}
</span>
<svg
width="12"
@@ -649,8 +652,8 @@ onBeforeRouteUpdate((to, from, next) => {
@click="selectAgentMode('normal')"
>
<div class="agent-mode-option-main">
- <span class="agent-mode-option-name">普通模式</span>
- <span class="agent-mode-option-desc">基于知识库的 RAG 问答</span>
+ <span class="agent-mode-option-name">{{ $t('input.normalMode') }}</span>
+ <span class="agent-mode-option-desc">{{ $t('input.normalModeDesc') }}</span>
</div>
<svg
v-if="!isAgentEnabled"
@@ -672,8 +675,8 @@ onBeforeRouteUpdate((to, from, next) => {
@click="selectAgentMode('agent')"
>
<div class="agent-mode-option-main">
- <span class="agent-mode-option-name">Agent 模式</span>
- <span class="agent-mode-option-desc">ReAct 推理框架,多步思考</span>
+ <span class="agent-mode-option-name">{{ $t('input.agentMode') }}</span>
+ <span class="agent-mode-option-desc">{{ $t('input.agentModeDesc') }}</span>
</div>
<svg
v-if="isAgentEnabled"
@@ -686,7 +689,7 @@ onBeforeRouteUpdate((to, from, next) => {
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
</svg>
<div v-if="!settingsStore.isAgentReady && !isAgentEnabled" class="agent-mode-warning">
- <t-tooltip content="Agent 未就绪,请先在设置中完成配置" placement="left">
+ <t-tooltip :content="$t('input.agentNotReadyTooltip')" placement="left">
<t-icon name="error-circle" class="warning-icon" />
</t-tooltip>
</div>
@@ -697,7 +700,7 @@ onBeforeRouteUpdate((to, from, next) => {
@click.prevent="handleGoToAgentSettings"
class="agent-mode-link"
>
- 前往设置 →
+ {{ $t('input.goToSettings') }}
</a>
</div>
</div>
@@ -707,10 +710,10 @@ onBeforeRouteUpdate((to, from, next) => {
<!-- WebSearch 开关按钮 -->
<t-tooltip placement="top">
<template #content>
- <span v-if="isWebSearchConfigured">{{ isWebSearchEnabled ? '关闭网络搜索' : '开启网络搜索' }}</span>
+ <span v-if="isWebSearchConfigured">{{ isWebSearchEnabled ? $t('input.webSearch.toggleOff') : $t('input.webSearch.toggleOn') }}</span>
<div v-else class="websearch-tooltip-disabled">
- <span>未配置网络搜索引擎</span>
- <a href="#" @click.prevent="handleGoToWebSearchSettings">前往设置 →</a>
+ <span>{{ $t('input.webSearch.notConfigured') }}</span>
+ <a href="#" @click.prevent="handleGoToWebSearchSettings">{{ $t('input.goToSettings') }}</a>
</div>
</template>
<div
@@ -745,7 +748,7 @@ onBeforeRouteUpdate((to, from, next) => {
>
<img :src="getImgSrc('at-icon.svg')" alt="@" class="control-icon" />
<span class="kb-btn-text">
- {{ selectedKbIds.length > 0 ? `知识库(${selectedKbIds.length})` : '知识库' }}
+ {{ selectedKbIds.length > 0 ? $t('input.knowledgeBaseWithCount', { count: selectedKbIds.length }) : $t('input.knowledgeBase') }}
</span>
<svg
width="12"
@@ -778,8 +781,8 @@ onBeforeRouteUpdate((to, from, next) => {
<div v-if="selectedKbIds.length > 0" class="model-display">
<!-- Agent 模式:只读显示 Thinking 模型 -->
<div v-if="isAgentEnabled" class="model-badge">
- <span class="model-label">Thinking:</span>
- <span class="model-name">{{ thinkingModelName || '未配置' }}</span>
+ <span class="model-label">{{ $t('input.thinkingLabel') }}</span>
+ <span class="model-name">{{ thinkingModelName || $t('input.notConfigured') }}</span>
</div>
<!-- 非 Agent 模式:可选择的模型下拉 -->
@@ -791,7 +794,7 @@ onBeforeRouteUpdate((to, from, next) => {
@click.stop="toggleModelSelector"
>
<span class="model-btn-text">
- {{ selectedModel ? selectedModel.name : '模型' }}
+ {{ selectedModel ? selectedModel.name : $t('input.model') }}
</span>
<svg
width="12"
@@ -823,7 +826,7 @@ onBeforeRouteUpdate((to, from, next) => {
>
<div class="model-option-main">
<span class="model-option-name">{{ model.name }}</span>
- <span v-if="model.source === 'remote'" class="model-badge-remote">远程</span>
+ <span v-if="model.source === 'remote'" class="model-badge-remote">{{ $t('input.remote') }}</span>
<span v-else-if="model.parameters?.parameter_size" class="model-badge-local">
{{ model.parameters.parameter_size }}
</span>
@@ -833,7 +836,7 @@ onBeforeRouteUpdate((to, from, next) => {
</div>
</div>
<div v-if="availableModels.length === 0" class="model-option empty">
- 暂无可用模型
+ {{ $t('input.noModel') }}
</div>
</div>
</div>
@@ -847,7 +850,7 @@ onBeforeRouteUpdate((to, from, next) => {
<!-- 停止按钮(仅在回复中时显示) -->
<t-tooltip
v-if="isReplying"
- content="停止生成"
+ :content="$t('input.stopGeneration')"
placement="top"
>
<div
@@ -867,7 +870,7 @@ onBeforeRouteUpdate((to, from, next) => {
class="control-btn send-btn"
:class="{ 'disabled': !query.length || selectedKbIds.length === 0 }"
>
- <img src="../assets/img/sending-aircraft.svg" alt="发送" />
+ <img src="../assets/img/sending-aircraft.svg" :alt="$t('input.send')" />
</div>
</div>
</div>
diff --git a/frontend/src/components/KnowledgeBaseSelector.vue b/frontend/src/components/KnowledgeBaseSelector.vue
index 34f3ef5de..c77ea5470 100644
--- a/frontend/src/components/KnowledgeBaseSelector.vue
+++ b/frontend/src/components/KnowledgeBaseSelector.vue
@@ -7,7 +7,7 @@
ref="searchInput"
v-model="searchQuery"
type="text"
- placeholder="搜索知识库..."
+ :placeholder="$t('knowledgeBase.searchPlaceholder')"
class="kb-search-input"
@keydown.down.prevent="moveSelection(1)"
@keydown.up.prevent="moveSelection(-1)"
@@ -33,20 +33,20 @@
</div>
<div class="kb-name-wrap">
<span class="kb-name">{{ kb.name }}</span>
- <span class="kb-docs" v-if="kb.docsCount !== undefined">{{ kb.docsCount }} docs</span>
+ <span class="kb-docs" v-if="kb.docsCount !== undefined">{{ kb.docsCount }} {{ $t('knowledgeBase.documents') }}</span>
</div>
</div>
</div>
<div v-if="filteredKnowledgeBases.length === 0" class="kb-empty">
- {{ searchQuery ? '未找到匹配的知识库' : '暂无可用知识库' }}
+ {{ searchQuery ? $t('knowledgeBase.noMatch') : $t('knowledgeBase.noKnowledge') }}
</div>
</div>
<!-- 底部操作 -->
<div class="kb-actions">
- <button @click="selectAll" class="kb-btn">全选</button>
- <button @click="clearAll" class="kb-btn">清空</button>
+ <button @click="selectAll" class="kb-btn">{{ $t('common.selectAll') }}</button>
+ <button @click="clearAll" class="kb-btn">{{ $t('common.clear') }}</button>
</div>
</div>
</div>
@@ -56,6 +56,7 @@
import { ref, computed, watch, nextTick } from 'vue'
import { useSettingsStore } from '@/stores/settings'
import { listKnowledgeBases } from '@/api/knowledge-base'
+import { useI18n } from 'vue-i18n'
interface KnowledgeBase {
id: string
@@ -65,6 +66,8 @@ interface KnowledgeBase {
summary_model_id?: string
}
+const { t } = useI18n()
+
const props = defineProps<{
visible: boolean
anchorEl?: any | null // 支持 DOM 节点、ref、组件实例
@@ -151,7 +154,7 @@ const loadKnowledgeBases = async () => {
const res: any = await listKnowledgeBases()
if (res?.data && Array.isArray(res.data)) knowledgeBases.value = res.data
} catch (e) {
- console.error('加载知识库失败', e)
+ console.error(t('knowledgeBase.loadingFailed'), e)
}
}
diff --git a/frontend/src/components/ModelEditorDialog.vue b/frontend/src/components/ModelEditorDialog.vue
index 78a7bc800..39a4a042f 100644
--- a/frontend/src/components/ModelEditorDialog.vue
+++ b/frontend/src/components/ModelEditorDialog.vue
@@ -4,7 +4,7 @@
<div v-if="dialogVisible" class="model-editor-overlay" @click.self="handleCancel">
<div class="model-editor-modal">
<!-- 关闭按钮 -->
- <button class="close-btn" @click="handleCancel" aria-label="关闭">
+ <button class="close-btn" @click="handleCancel" :aria-label="$t('common.close')">
<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
<path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>
@@ -12,7 +12,7 @@
<!-- 标题区域 -->
<div class="modal-header">
- <h2 class="modal-title">{{ isEdit ? '编辑模型' : '添加模型' }}</h2>
+ <h2 class="modal-title">{{ isEdit ? $t('model.editor.editTitle') : $t('model.editor.addTitle') }}</h2>
<p class="modal-desc">{{ getModalDescription() }}</p>
</div>
@@ -21,16 +21,16 @@
<t-form ref="formRef" :data="formData" :rules="rules" layout="vertical">
<!-- 模型来源 -->
<div class="form-item">
- <label class="form-label required">模型来源</label>
+ <label class="form-label required">{{ $t('model.editor.sourceLabel') }}</label>
<t-radio-group v-model="formData.source">
- <t-radio value="local">Ollama (本地)</t-radio>
- <t-radio value="remote">Remote API (远程)</t-radio>
+ <t-radio value="local">{{ $t('model.editor.sourceLocal') }}</t-radio>
+ <t-radio value="remote">{{ $t('model.editor.sourceRemote') }}</t-radio>
</t-radio-group>
</div>
<!-- Ollama 本地模型选择器 -->
<div v-if="formData.source === 'local'" class="form-item">
- <label class="form-label required">模型名称</label>
+ <label class="form-label required">{{ $t('model.modelName') }}</label>
<div class="model-select-row">
<t-select
v-model="formData.modelName"
@@ -39,7 +39,7 @@
:style="downloading ? `--progress: ${downloadProgress}%` : ''"
filterable
:filter="handleModelFilter"
- placeholder="搜索模型..."
+ :placeholder="$t('model.searchPlaceholder')"
@focus="loadOllamaModels"
@visible-change="handleDropdownVisibleChange"
>
@@ -61,12 +61,12 @@
<t-option
v-if="showDownloadOption"
:value="`__download__${searchKeyword}`"
- :label="`下载: ${searchKeyword}`"
+ :label="$t('model.editor.downloadLabel', { keyword: searchKeyword })"
class="download-option"
>
<div class="model-option download">
<t-icon name="download" class="download-icon" />
- <span class="model-name">下载: {{ searchKeyword }}</span>
+ <span class="model-name">{{ $t('model.editor.downloadLabel', { keyword: searchKeyword }) }}</span>
</div>
</t-option>
@@ -88,14 +88,14 @@
class="refresh-btn"
>
<t-icon name="refresh" />
- 刷新列表
+ {{ $t('model.editor.refreshList') }}
</t-button>
</div>
</div>
<!-- Remote API 和 VLLM 保持原有的 input -->
<div v-else class="form-item">
- <label class="form-label required">模型名称</label>
+ <label class="form-label required">{{ $t('model.modelName') }}</label>
<t-input
v-model="formData.modelName"
:placeholder="getModelNamePlaceholder()"
@@ -105,25 +105,25 @@
<!-- Remote API 配置 -->
<template v-if="formData.source === 'remote'">
<div class="form-item">
- <label class="form-label required">Base URL</label>
+ <label class="form-label required">{{ $t('model.editor.baseUrlLabel') }}</label>
<t-input
v-model="formData.baseUrl"
- :placeholder="modelType === 'vllm' ? '如:http://localhost:11434/v1' : '如:https://api.openai.com/v1'"
+ :placeholder="getBaseUrlPlaceholder()"
/>
</div>
<div class="form-item">
- <label class="form-label">API Key (可选)</label>
+ <label class="form-label">{{ $t('model.editor.apiKeyOptional') }}</label>
<t-input
v-model="formData.apiKey"
type="password"
- placeholder="输入 API Key"
+ :placeholder="$t('model.editor.apiKeyPlaceholder')"
/>
</div>
<!-- Remote API 校验 -->
<div class="form-item">
- <label class="form-label">连接测试</label>
+ <label class="form-label">{{ $t('model.editor.connectionTest') }}</label>
<div class="api-test-section">
<t-button
variant="outline"
@@ -143,7 +143,7 @@
class="status-icon unavailable"
/>
</template>
- {{ checking ? '测试中...' : '测试连接' }}
+ {{ checking ? $t('model.editor.testing') : $t('model.editor.testConnection') }}
</t-button>
<span v-if="remoteChecked" :class="['test-message', remoteAvailable ? 'success' : 'error']">
{{ remoteMessage }}
@@ -154,14 +154,14 @@
<!-- Embedding 专用:维度 -->
<div v-if="modelType === 'embedding'" class="form-item">
- <label class="form-label">向量维度</label>
+ <label class="form-label">{{ $t('model.editor.dimensionLabel') }}</label>
<div class="dimension-control">
<t-input
v-model.number="formData.dimension"
type="number"
:min="128"
:max="4096"
- placeholder="如:1536"
+ :placeholder="$t('model.editor.dimensionPlaceholder')"
:disabled="formData.source === 'local' && checking"
/>
<!-- Ollama 本地模型:自动检测维度按钮 -->
@@ -174,7 +174,7 @@
class="dimension-check-btn"
>
<t-icon name="refresh" />
- 检测维度
+ {{ $t('model.editor.checkDimension') }}
</t-button>
</div>
<p v-if="dimensionChecked && dimensionMessage" class="dimension-hint" :class="{ success: dimensionSuccess }">
@@ -184,7 +184,7 @@
<!-- 设为默认 -->
<div class="form-item">
- <t-checkbox v-model="formData.isDefault">设为默认模型</t-checkbox>
+ <t-checkbox v-model="formData.isDefault">{{ $t('model.editor.setAsDefault') }}</t-checkbox>
</div>
</t-form>
</div>
@@ -192,10 +192,10 @@
<!-- 底部按钮区域 -->
<div class="modal-footer">
<t-button theme="default" variant="outline" @click="handleCancel">
- 取消
+ {{ $t('common.cancel') }}
</t-button>
<t-button theme="primary" @click="handleConfirm" :loading="saving">
- 保存
+ {{ $t('common.save') }}
</t-button>
</div>
</div>
@@ -208,6 +208,7 @@
import { ref, watch, computed, onUnmounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { checkOllamaModels, checkRemoteModel, testEmbeddingModel, checkRerankModel, listOllamaModels, downloadOllamaModel, getDownloadProgress, type OllamaModelInfo } from '@/api/initialization'
+import { useI18n } from 'vue-i18n'
interface ModelFormData {
id: string
@@ -227,6 +228,8 @@ interface Props {
modelData?: ModelFormData | null
}
+const { t } = useI18n()
+
const props = withDefaults(defineProps<Props>(), {
visible: false,
modelData: null
@@ -277,16 +280,16 @@ const formData = ref<ModelFormData>({
isDefault: false
})
-const rules = {
+const rules = computed(() => ({
modelName: [
- { required: true, message: '请输入模型名称' },
+ { required: true, message: t('model.editor.validation.modelNameRequired') },
{
validator: (val: string) => {
if (!val || !val.trim()) {
- return { result: false, message: '模型名称不能为空' }
+ return { result: false, message: t('model.editor.validation.modelNameEmpty') }
}
if (val.trim().length > 100) {
- return { result: false, message: '模型名称不能超过100个字符' }
+ return { result: false, message: t('model.editor.validation.modelNameMax') }
}
return { result: true }
},
@@ -296,44 +299,49 @@ const rules = {
baseUrl: [
{
required: true,
- message: '请输入 Base URL',
+ message: t('model.editor.validation.baseUrlRequired'),
trigger: 'blur'
},
{
validator: (val: string) => {
if (!val || !val.trim()) {
- return { result: false, message: 'Base URL 不能为空' }
+ return { result: false, message: t('model.editor.validation.baseUrlEmpty') }
}
// 简单的 URL 格式校验
try {
new URL(val.trim())
return { result: true }
} catch {
- return { result: false, message: 'Base URL 格式不正确,请输入有效的 URL' }
+ return { result: false, message: t('model.editor.validation.baseUrlInvalid') }
}
},
trigger: 'blur'
}
]
-}
+}))
// 获取弹窗描述文字
const getModalDescription = () => {
- const typeDesc = {
- chat: '配置用于对话的大语言模型',
- embedding: '配置用于文本向量化的嵌入模型',
- rerank: '配置用于结果重排序的模型',
- vllm: '配置用于视觉理解和多模态的视觉语言模型'
- }
- return typeDesc[props.modelType] || '配置模型信息'
+ const key = `model.editor.description.${props.modelType}` as const
+ return t(key) || t('model.editor.description.default')
}
// 获取模型名称占位符
const getModelNamePlaceholder = () => {
if (props.modelType === 'vllm') {
- return formData.value.source === 'local' ? '如:llava:latest' : '如:gpt-4-vision-preview'
+ return formData.value.source === 'local'
+ ? t('model.editor.modelNamePlaceholder.localVllm')
+ : t('model.editor.modelNamePlaceholder.remoteVllm')
}
- return formData.value.source === 'local' ? '如:llama2:latest' : '如:gpt-4, claude-3-opus'
+ return formData.value.source === 'local'
+ ? t('model.editor.modelNamePlaceholder.local')
+ : t('model.editor.modelNamePlaceholder.remote')
+}
+
+const getBaseUrlPlaceholder = () => {
+ return props.modelType === 'vllm'
+ ? t('model.editor.baseUrlPlaceholderVllm')
+ : t('model.editor.baseUrlPlaceholder')
}
// 监听 visible 变化,初始化表单
@@ -417,8 +425,8 @@ const loadOllamaModels = async () => {
const models = await listOllamaModels()
ollamaModelList.value = models
} catch (error) {
- console.error('加载 Ollama 模型列表失败:', error)
- MessagePlugin.error('加载模型列表失败')
+ console.error(t('model.editor.loadModelListFailed'), error)
+ MessagePlugin.error(t('model.editor.loadModelListFailed'))
} finally {
loadingOllamaModels.value = false
}
@@ -428,7 +436,7 @@ const loadOllamaModels = async () => {
const refreshOllamaModels = async () => {
ollamaModelList.value = [] // 清空以强制重新加载
await loadOllamaModels()
- MessagePlugin.success('列表已刷新')
+ MessagePlugin.success(t('model.editor.listRefreshed'))
}
// 监听下拉框可见性变化
@@ -485,17 +493,17 @@ const checkOllamaDimension = async () => {
if (result.available && result.dimension) {
formData.value.dimension = result.dimension
- dimensionMessage.value = `检测成功,向量维度:${result.dimension}`
+ dimensionMessage.value = t('model.editor.dimensionDetected', { value: result.dimension })
MessagePlugin.success(dimensionMessage.value)
} else {
- dimensionMessage.value = result.message || '检测失败,请手动输入维度'
+ dimensionMessage.value = result.message || t('model.editor.dimensionFailed')
MessagePlugin.warning(dimensionMessage.value)
}
} catch (error: any) {
console.error('检测 Ollama 模型维度失败:', error)
dimensionChecked.value = true
dimensionSuccess.value = false
- dimensionMessage.value = error.message || '检测失败,请手动输入维度'
+ dimensionMessage.value = error.message || t('model.editor.dimensionFailed')
MessagePlugin.error(dimensionMessage.value)
} finally {
checking.value = false
@@ -505,7 +513,7 @@ const checkOllamaDimension = async () => {
// 检查 Remote API 连接(根据模型类型调用不同的接口)
const checkRemoteAPI = async () => {
if (!formData.value.modelName || !formData.value.baseUrl) {
- MessagePlugin.warning('请先填写模型标识和 Base URL')
+ MessagePlugin.warning(t('model.editor.fillModelAndUrl'))
return
}
@@ -539,7 +547,7 @@ const checkRemoteAPI = async () => {
// 如果测试成功且返回了维度,自动填充
if (result.available && result.dimension) {
formData.value.dimension = result.dimension
- MessagePlugin.info(`检测到向量维度:${result.dimension}`)
+ MessagePlugin.info(t('model.editor.remoteDimensionDetected', { value: result.dimension }))
}
break
@@ -563,13 +571,13 @@ const checkRemoteAPI = async () => {
break
default:
- MessagePlugin.error('不支持的模型类型')
+ MessagePlugin.error(t('model.editor.unsupportedModelType'))
return
}
remoteChecked.value = true
remoteAvailable.value = result.available || false
- remoteMessage.value = result.message || (result.available ? '连接成功' : '连接失败')
+ remoteMessage.value = result.message || (result.available ? t('model.editor.connectionSuccess') : t('model.editor.connectionFailed'))
if (result.available) {
MessagePlugin.success(remoteMessage.value)
@@ -580,7 +588,7 @@ const checkRemoteAPI = async () => {
console.error('Remote API 校验失败:', error)
remoteChecked.value = true
remoteAvailable.value = false
- remoteMessage.value = error.message || '连接失败,请检查配置'
+ remoteMessage.value = error.message || t('model.editor.connectionConfigError')
MessagePlugin.error(remoteMessage.value)
} finally {
checking.value = false
@@ -592,19 +600,19 @@ const handleConfirm = async () => {
try {
// 手动校验必填字段
if (!formData.value.modelName || !formData.value.modelName.trim()) {
- MessagePlugin.warning('请输入模型名称')
+ MessagePlugin.warning(t('model.editor.validation.modelNameRequired'))
return
}
if (formData.value.modelName.trim().length > 100) {
- MessagePlugin.warning('模型名称不能超过100个字符')
+ MessagePlugin.warning(t('model.editor.validation.modelNameMax'))
return
}
// 如果是 remote 类型,必须填写 baseUrl
if (formData.value.source === 'remote') {
if (!formData.value.baseUrl || !formData.value.baseUrl.trim()) {
- MessagePlugin.warning('Remote API 类型必须填写 Base URL')
+ MessagePlugin.warning(t('model.editor.remoteBaseUrlRequired'))
return
}
@@ -612,7 +620,7 @@ const handleConfirm = async () => {
try {
new URL(formData.value.baseUrl.trim())
} catch {
- MessagePlugin.warning('Base URL 格式不正确,请输入有效的 URL')
+ MessagePlugin.warning(t('model.editor.validation.baseUrlInvalid'))
return
}
}
@@ -659,7 +667,7 @@ watch(() => formData.value.modelName, async (newValue, oldValue) => {
newValue !== oldValue &&
oldValue !== '') {
// 提示用户可以检测维度
- MessagePlugin.info('模型已选择,点击"检测维度"按钮自动获取向量维度')
+ MessagePlugin.info(t('model.editor.dimensionHint'))
}
})
@@ -674,7 +682,7 @@ const startDownload = async (modelName: string) => {
const result = await downloadOllamaModel(modelName)
const taskId = result.taskId
- MessagePlugin.success(`开始下载 ${modelName}`)
+ MessagePlugin.success(t('model.editor.downloadStarted', { name: modelName }))
// 轮询下载进度
downloadInterval = setInterval(async () => {
@@ -688,7 +696,7 @@ const startDownload = async (modelName: string) => {
downloadInterval = null
downloading.value = false
- MessagePlugin.success(`${modelName} 下载完成`)
+ MessagePlugin.success(t('model.editor.downloadCompleted', { name: modelName }))
// 刷新模型列表
await loadOllamaModels()
@@ -705,7 +713,7 @@ const startDownload = async (modelName: string) => {
clearInterval(downloadInterval)
downloadInterval = null
downloading.value = false
- MessagePlugin.error(progress.message || `${modelName} 下载失败`)
+ MessagePlugin.error(progress.message || t('model.editor.downloadFailed', { name: modelName }))
downloadProgress.value = 0
currentDownloadModel.value = ''
}
@@ -718,7 +726,7 @@ const startDownload = async (modelName: string) => {
downloading.value = false
downloadProgress.value = 0
currentDownloadModel.value = ''
- MessagePlugin.error(error.message || '启动下载失败')
+ MessagePlugin.error(error.message || t('model.editor.downloadStartFailed'))
}
}
diff --git a/frontend/src/components/ModelSelector.vue b/frontend/src/components/ModelSelector.vue
index 3375cd880..49ce12012 100644
--- a/frontend/src/components/ModelSelector.vue
+++ b/frontend/src/components/ModelSelector.vue
@@ -3,7 +3,7 @@
<t-select
:value="selectedModelId"
@change="handleModelChange"
- :placeholder="placeholder"
+ :placeholder="placeholderText"
:disabled="disabled"
:loading="loading"
filterable
@@ -19,7 +19,7 @@
<div class="model-option">
<t-icon name="check-circle-filled" class="model-icon" />
<span class="model-name">{{ model.name }}</span>
- <t-tag v-if="model.is_default" size="small" theme="success">默认</t-tag>
+ <t-tag v-if="model.is_default" size="small" theme="success">{{ $t('model.defaultTag') }}</t-tag>
</div>
</t-option>
@@ -31,7 +31,7 @@
>
<div class="model-option add">
<t-icon name="add" class="add-icon" />
- <span class="model-name">前往全局设置添加模型</span>
+ <span class="model-name">{{ $t('model.addModelInSettings') }}</span>
</div>
</t-option>
</t-select>
@@ -42,6 +42,7 @@
import { ref, computed, watch, onMounted } from 'vue'
import { listModels, type ModelConfig } from '@/api/model'
import { MessagePlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
interface Props {
modelType: 'KnowledgeQA' | 'Embedding' | 'Rerank' | 'VLLM'
@@ -54,7 +55,7 @@ interface Props {
const props = withDefaults(defineProps<Props>(), {
disabled: false,
- placeholder: '请选择模型'
+ placeholder: ''
})
const emit = defineEmits<{
@@ -64,6 +65,11 @@ const emit = defineEmits<{
const models = ref<ModelConfig[]>([])
const loading = ref(false)
+const { t } = useI18n()
+
+const placeholderText = computed(() => {
+ return props.placeholder || t('model.selectModelPlaceholder')
+})
// 监听 allModels 变化,自动过滤当前类型的模型
watch(() => props.allModels, (newModels) => {
@@ -94,8 +100,8 @@ const loadModels = async () => {
models.value = []
}
} catch (error) {
- console.error('加载模型列表失败:', error)
- MessagePlugin.error('加载模型列表失败')
+ console.error(t('model.loadFailed'), error)
+ MessagePlugin.error(t('model.loadFailed'))
models.value = []
} finally {
loading.value = false
diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vue
index 17069c520..74e028434 100644
--- a/frontend/src/components/UserMenu.vue
+++ b/frontend/src/components/UserMenu.vue
@@ -3,7 +3,7 @@
<!-- 用户按钮 -->
<div class="user-button" @click="toggleMenu">
<div class="user-avatar">
- <img v-if="userAvatar" :src="userAvatar" alt="用户头像" />
+ <img v-if="userAvatar" :src="userAvatar" :alt="$t('common.avatar')" />
<span v-else class="avatar-placeholder">{{ userInitial }}</span>
</div>
<div class="user-info">
@@ -18,7 +18,7 @@
<div v-if="menuVisible" class="user-dropdown" @click.stop>
<div class="menu-item" @click="handleQuickNav('models')">
<t-icon name="control-platform" class="menu-icon" />
- <span>模型配置</span>
+ <span>{{ $t('settings.modelConfig') }}</span>
</div>
<div class="menu-item" @click="handleQuickNav('ollama')">
<t-icon name="server" class="menu-icon" />
@@ -27,25 +27,49 @@
<div class="menu-divider"></div>
<div class="menu-item" @click="handleSettings">
<t-icon name="setting" class="menu-icon" />
- <span>全部设置</span>
+ <span>{{ $t('general.allSettings') }}</span>
</div>
<div class="menu-divider"></div>
<div class="menu-item" @click="openApiDoc">
<t-icon name="book" class="menu-icon" />
- <span>API 文档</span>
+ <span class="menu-text-with-icon">
+ <span>{{ $t('tenant.apiDocument') }}</span>
+ <svg class="menu-external-icon" viewBox="0 0 16 16" aria-hidden="true">
+ <path
+ fill="currentColor"
+ d="M12.667 8a.667.667 0 0 1 .666.667v4a2.667 2.667 0 0 1-2.666 2.666H4.667a2.667 2.667 0 0 1-2.667-2.666V5.333a2.667 2.667 0 0 1 2.667-2.666h4a.667.667 0 1 1 0 1.333h-4a1.333 1.333 0 0 0-1.333 1.333v7.334A1.333 1.333 0 0 0 4.667 13.333h6a1.333 1.333 0 0 0 1.333-1.333v-4A.667.667 0 0 1 12.667 8Zm2.666-6.667v4a.667.667 0 0 1-1.333 0V3.276l-5.195 5.195a.667.667 0 0 1-.943-.943l5.195-5.195h-2.057a.667.667 0 0 1 0-1.333h4a.667.667 0 0 1 .666.666Z"
+ />
+ </svg>
+ </span>
</div>
<div class="menu-item" @click="openWebsite">
<t-icon name="home" class="menu-icon" />
- <span>官网</span>
+ <span class="menu-text-with-icon">
+ <span>{{ $t('common.website') }}</span>
+ <svg class="menu-external-icon" viewBox="0 0 16 16" aria-hidden="true">
+ <path
+ fill="currentColor"
+ d="M12.667 8a.667.667 0 0 1 .666.667v4a2.667 2.667 0 0 1-2.666 2.666H4.667a2.667 2.667 0 0 1-2.667-2.666V5.333a2.667 2.667 0 0 1 2.667-2.666h4a.667.667 0 1 1 0 1.333h-4a1.333 1.333 0 0 0-1.333 1.333v7.334A1.333 1.333 0 0 0 4.667 13.333h6a1.333 1.333 0 0 0 1.333-1.333v-4A.667.667 0 0 1 12.667 8Zm2.666-6.667v4a.667.667 0 0 1-1.333 0V3.276l-5.195 5.195a.667.667 0 0 1-.943-.943l5.195-5.195h-2.057a.667.667 0 0 1 0-1.333h4a.667.667 0 0 1 .666.666Z"
+ />
+ </svg>
+ </span>
</div>
<div class="menu-item" @click="openGithub">
<t-icon name="logo-github" class="menu-icon" />
- <span>GitHub</span>
+ <span class="menu-text-with-icon">
+ <span>GitHub</span>
+ <svg class="menu-external-icon" viewBox="0 0 16 16" aria-hidden="true">
+ <path
+ fill="currentColor"
+ d="M12.667 8a.667.667 0 0 1 .666.667v4a2.667 2.667 0 0 1-2.666 2.666H4.667a2.667 2.667 0 0 1-2.667-2.666V5.333a2.667 2.667 0 0 1 2.667-2.666h4a.667.667 0 1 1 0 1.333h-4a1.333 1.333 0 0 0-1.333 1.333v7.334A1.333 1.333 0 0 0 4.667 13.333h6a1.333 1.333 0 0 0 1.333-1.333v-4A.667.667 0 0 1 12.667 8Zm2.666-6.667v4a.667.667 0 0 1-1.333 0V3.276l-5.195 5.195a.667.667 0 0 1-.943-.943l5.195-5.195h-2.057a.667.667 0 0 1 0-1.333h4a.667.667 0 0 1 .666.666Z"
+ />
+ </svg>
+ </span>
</div>
<div class="menu-divider"></div>
<div class="menu-item danger" @click="handleLogout">
<t-icon name="logout" class="menu-icon" />
- <span>注销</span>
+ <span>{{ $t('auth.logout') }}</span>
</div>
</div>
</Transition>
@@ -59,6 +83,9 @@ import { useUIStore } from '@/stores/ui'
import { useAuthStore } from '@/stores/auth'
import { MessagePlugin } from 'tdesign-vue-next'
import { getCurrentUser, logout as logoutApi } from '@/api/auth'
+import { useI18n } from 'vue-i18n'
+
+const { t } = useI18n()
const router = useRouter()
const uiStore = useUIStore()
@@ -142,7 +169,7 @@ const handleLogout = async () => {
// 清理所有状态和本地存储
authStore.logout()
- MessagePlugin.success('已退出登录')
+ MessagePlugin.success(t('auth.logout'))
// 跳转到登录页
router.push('/login')
@@ -154,7 +181,7 @@ const loadUserInfo = async () => {
const response = await getCurrentUser()
if (response.success && response.data && response.data.user) {
userInfo.value = {
- username: response.data.user.username || '用户',
+ username: response.data.user.username || t('common.info'),
email: response.data.user.email || '[email protected]',
avatar: response.data.user.avatar || ''
}
@@ -304,6 +331,34 @@ onUnmounted(() => {
font-size: 16px;
color: #666666;
}
+
+ .menu-text-with-icon {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ color: inherit;
+ min-width: 0;
+
+ span {
+ display: inline-flex;
+ align-items: center;
+ min-width: 0;
+ }
+ }
+
+ .menu-external-icon {
+ width: 14px;
+ height: 14px;
+ color: #9ca3af;
+ flex-shrink: 0;
+ transition: color 0.2s ease;
+ pointer-events: none;
+ }
+
+ &:hover .menu-external-icon {
+ color: #07c05f;
+ }
}
.menu-divider {
diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue
index 6a96c3417..f62bdcf47 100644
--- a/frontend/src/components/doc-content.vue
+++ b/frontend/src/components/doc-content.vue
@@ -5,6 +5,9 @@ import { downKnowledgeDetails } from "@/api/knowledge-base/index";
import { MessagePlugin } from "tdesign-vue-next";
import picturePreview from '@/components/picture-preview.vue';
import { sanitizeHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL } from '@/utils/security';
+import { useI18n } from 'vue-i18n';
+
+const { t } = useI18n();
marked.use({
mangle: false,
@@ -41,7 +44,7 @@ const checkImage = (url) => {
renderer.image = function (href, title, text) {
// 安全地处理图片链接
if (!isValidImageURL(href)) {
- return `<p>无效的图片链接</p>`;
+ return `<p>${t('error.invalidImageLink')}</p>`;
}
// 使用安全的图片创建函数
@@ -120,7 +123,7 @@ const downloadFile = () => {
}
})
.catch((err) => {
- MessagePlugin.error("获取文件失败!");
+ MessagePlugin.error(t('file.downloadFailed'));
});
};
const handleDetailsScroll = () => {
@@ -144,7 +147,7 @@ const handleDetailsScroll = () => {
}}</template>
<div class="doc_box">
<a :href="url" style="display: none" ref="down" :download="details.title"></a>
- <span class="label">文档标题</span>
+ <span class="label">{{ $t('knowledgeBase.fileName') }}</span>
<div class="download_box">
<span class="doc_t">{{ details.title }}</span>
<div class="icon_box" @click="downloadFile()">
@@ -153,10 +156,10 @@ const handleDetailsScroll = () => {
</div>
</div>
<div class="content_header">
- <span class="label">文档内容</span>
- <span class="time"> 更新时间:{{ details.time }} </span>
+ <span class="label">{{ $t('knowledgeBase.fileContent') }}</span>
+ <span class="time"> {{ $t('knowledgeBase.uploadTime') }}:{{ details.time }} </span>
</div>
- <div v-if="details.md.length == 0" class="no_content">暂无数据</div>
+ <div v-if="details.md.length == 0" class="no_content">{{ $t('common.noData') }}</div>
<div v-else class="content" v-for="(item, index) in details.md" :key="index" :style="index % 2 !== 0
? 'background: #07c05f26;'
: 'background: #3032360f;'
@@ -164,8 +167,8 @@ const handleDetailsScroll = () => {
<div class="md-content" v-html="processMarkdown(item.content)"></div>
</div>
<template #footer>
- <t-button @click="handleClose">确定</t-button>
- <t-button theme="default" @click="handleClose">取消</t-button>
+ <t-button @click="handleClose">{{ $t('common.confirm') }}</t-button>
+ <t-button theme="default" @click="handleClose">{{ $t('common.cancel') }}</t-button>
</template>
</t-drawer>
<picturePreview :reviewImg="reviewImg" :reviewUrl="reviewUrl" @closePreImg="closePreImg"></picturePreview>
diff --git a/frontend/src/components/empty-knowledge.vue b/frontend/src/components/empty-knowledge.vue
index 1310c8819..086a7c2e0 100644
--- a/frontend/src/components/empty-knowledge.vue
+++ b/frontend/src/components/empty-knowledge.vue
@@ -1,11 +1,13 @@
<script setup lang="ts">
+import { useI18n } from 'vue-i18n'
+const { t } = useI18n()
</script>
<template>
<div class="empty">
<img class="empty-img" src="@/assets/img/upload.svg" alt="">
- <span class="empty-txt">知识为空,拖放上传</span>
- <span class="empty-type-txt">pdf、doc 格式文件,不超过10M</span>
- <span class="empty-type-txt">text、markdown格式文件,不超过200K</span>
+ <span class="empty-txt">{{ $t('knowledgeBase.emptyKnowledgeDragDrop') }}</span>
+ <span class="empty-type-txt">{{ $t('knowledgeBase.pdfDocFormat') }}</span>
+ <span class="empty-type-txt">{{ $t('knowledgeBase.textMarkdownFormat') }}</span>
</div>
</template>
<style scoped lang="less">
diff --git a/frontend/src/components/manual-knowledge-editor.vue b/frontend/src/components/manual-knowledge-editor.vue
index 66fa83050..6d2fd082b 100644
--- a/frontend/src/components/manual-knowledge-editor.vue
+++ b/frontend/src/components/manual-knowledge-editor.vue
@@ -5,6 +5,7 @@ import { MessagePlugin } from 'tdesign-vue-next'
import { useUIStore } from '@/stores/ui'
import { listKnowledgeBases, getKnowledgeDetails, createManualKnowledge, updateManualKnowledge } from '@/api/knowledge-base'
import { sanitizeHTML, safeMarkdownToHTML } from '@/utils/security'
+import { useI18n } from 'vue-i18n'
interface KnowledgeBaseOption {
label: string
@@ -23,6 +24,7 @@ interface KnowledgeDetailResponse {
type ManualStatus = 'draft' | 'publish'
const uiStore = useUIStore()
+const { t } = useI18n()
const visible = computed({
get: () => uiStore.manualEditorVisible,
@@ -205,7 +207,7 @@ const applyHeading = (level: number) => {
const hashes = '#'.repeat(level)
transformSelectedLines((line) => {
const trimmed = line.replace(/^#+\s*/, '').trim()
- const content = trimmed || `标题${level}`
+ const content = trimmed || t('manualEditor.placeholders.heading', { level })
return `${hashes} ${content}`
})
}
@@ -217,7 +219,7 @@ const applyBulletList = () => {
transformSelectedLines((line) => {
const trimmed = line.trim()
const content = trimmed.replace(listPrefixPattern, '').trim()
- return `- ${content || '列表项'}`
+ return `- ${content || t('manualEditor.placeholders.listItem')}`
})
}
@@ -225,7 +227,7 @@ const applyOrderedList = () => {
transformSelectedLines((line, index) => {
const trimmed = line.trim()
const content = trimmed.replace(listPrefixPattern, '').trim()
- return `${index + 1}. ${content || '列表项'}`
+ return `${index + 1}. ${content || t('manualEditor.placeholders.listItem')}`
})
}
@@ -233,19 +235,19 @@ const applyTaskList = () => {
transformSelectedLines((line) => {
const trimmed = line.trim()
const content = trimmed.replace(listPrefixPattern, '').trim()
- return `- [ ] ${content || '任务项'}`
+ return `- [ ] ${content || t('manualEditor.placeholders.taskItem')}`
})
}
const applyBlockquote = () => {
transformSelectedLines((line) => {
const trimmed = line.trim().replace(/^>\s?/, '').trim()
- return `> ${trimmed || '引用内容'}`
+ return `> ${trimmed || t('manualEditor.placeholders.quote')}`
})
}
const insertCodeBlock = () => {
- const placeholder = '代码内容'
+ const placeholder = t('manualEditor.placeholders.code')
const block = `\n\`\`\`\n${placeholder}\n\`\`\`\n`
const startOffset = block.indexOf(placeholder)
insertBlock(block, startOffset, startOffset + placeholder.length)
@@ -256,9 +258,10 @@ const insertHorizontalRule = () => {
}
const insertTable = () => {
- const template = '\n| 列1 | 列2 |\n| --- | --- |\n| 内容 | 内容 |\n'
- const placeholderIndex = template.indexOf('内容')
- insertBlock(template, placeholderIndex, placeholderIndex + 2)
+ const cell = t('manualEditor.table.cell')
+ const template = `\n| ${t('manualEditor.table.column1')} | ${t('manualEditor.table.column2')} |\n| --- | --- |\n| ${cell} | ${cell} |\n`
+ const placeholderIndex = template.indexOf(cell)
+ insertBlock(template, placeholderIndex, placeholderIndex + cell.length)
}
const insertLink = () => {
@@ -266,7 +269,7 @@ const insertLink = () => {
const { start, end } = getSelectionRange()
const { safeStart, safeEnd } = clampRange(start, end, value.length)
const selectedText =
- safeEnd > safeStart ? value.slice(safeStart, safeEnd) : '链接文本'
+ safeEnd > safeStart ? value.slice(safeStart, safeEnd) : t('manualEditor.placeholders.linkText')
const urlPlaceholder = 'https://'
const result =
value.slice(0, safeStart) +
@@ -281,7 +284,7 @@ const insertImage = () => {
const value = form.content ?? ''
const { start, end } = getSelectionRange()
const { safeStart, safeEnd } = clampRange(start, end, value.length)
- const altText = safeEnd > safeStart ? value.slice(safeStart, safeEnd) : '描述'
+ const altText = safeEnd > safeStart ? value.slice(safeStart, safeEnd) : t('manualEditor.placeholders.imageAlt')
const urlPlaceholder = 'https://'
const result =
value.slice(0, safeStart) +
@@ -304,49 +307,55 @@ type ToolbarGroup = {
buttons: ToolbarButton[]
}
-const toolbarGroups: ToolbarGroup[] = [
+const toolbarGroups = computed<ToolbarGroup[]>(() => [
{
key: 'format',
buttons: [
- { key: 'bold', icon: 'textformat-bold', tooltip: '加粗', action: () => wrapSelection('**', '**', '加粗文本') },
- { key: 'italic', icon: 'textformat-italic', tooltip: '斜体', action: () => wrapSelection('*', '*', '斜体文本') },
- { key: 'strike', icon: 'textformat-strikethrough', tooltip: '删除线', action: () => wrapSelection('~~', '~~', '删除线') },
- { key: 'inline-code', icon: 'code', tooltip: '行内代码', action: () => wrapSelection('`', '`', 'code') },
+ { key: 'bold', icon: 'textformat-bold', tooltip: t('manualEditor.toolbar.bold'), action: () => wrapSelection('**', '**', t('manualEditor.placeholders.bold')) },
+ { key: 'italic', icon: 'textformat-italic', tooltip: t('manualEditor.toolbar.italic'), action: () => wrapSelection('*', '*', t('manualEditor.placeholders.italic')) },
+ { key: 'strike', icon: 'textformat-strikethrough', tooltip: t('manualEditor.toolbar.strike'), action: () => wrapSelection('~~', '~~', t('manualEditor.placeholders.strike')) },
+ { key: 'inline-code', icon: 'code', tooltip: t('manualEditor.toolbar.inlineCode'), action: () => wrapSelection('`', '`', t('manualEditor.placeholders.inlineCode')) },
],
},
{
key: 'heading',
buttons: [
- { key: 'h1', icon: 'numbers-1', tooltip: '一级标题', action: () => applyHeading(1) },
- { key: 'h2', icon: 'numbers-2', tooltip: '二级标题', action: () => applyHeading(2) },
- { key: 'h3', icon: 'numbers-3', tooltip: '三级标题', action: () => applyHeading(3) },
+ { key: 'h1', icon: 'numbers-1', tooltip: t('manualEditor.toolbar.heading1'), action: () => applyHeading(1) },
+ { key: 'h2', icon: 'numbers-2', tooltip: t('manualEditor.toolbar.heading2'), action: () => applyHeading(2) },
+ { key: 'h3', icon: 'numbers-3', tooltip: t('manualEditor.toolbar.heading3'), action: () => applyHeading(3) },
],
},
{
key: 'list',
buttons: [
- { key: 'ul', icon: 'view-list', tooltip: '无序列表', action: applyBulletList },
- { key: 'ol', icon: 'list-numbered', tooltip: '有序列表', action: applyOrderedList },
- { key: 'task', icon: 'check-rectangle', tooltip: '任务列表', action: applyTaskList },
- { key: 'quote', icon: 'quote', tooltip: '引用', action: applyBlockquote },
+ { key: 'ul', icon: 'view-list', tooltip: t('manualEditor.toolbar.bulletList'), action: applyBulletList },
+ { key: 'ol', icon: 'list-numbered', tooltip: t('manualEditor.toolbar.orderedList'), action: applyOrderedList },
+ { key: 'task', icon: 'check-rectangle', tooltip: t('manualEditor.toolbar.taskList'), action: applyTaskList },
+ { key: 'quote', icon: 'quote', tooltip: t('manualEditor.toolbar.blockquote'), action: applyBlockquote },
],
},
{
key: 'insert',
buttons: [
- { key: 'codeblock', icon: 'code-1', tooltip: '代码块', action: insertCodeBlock },
- { key: 'link', icon: 'link', tooltip: '插入链接', action: insertLink },
- { key: 'image', icon: 'image', tooltip: '插入图片', action: insertImage },
- { key: 'table', icon: 'table', tooltip: '插入表格', action: insertTable },
- { key: 'hr', icon: 'component-divider-horizontal', tooltip: '分割线', action: insertHorizontalRule },
+ { key: 'codeblock', icon: 'code-1', tooltip: t('manualEditor.toolbar.codeBlock'), action: insertCodeBlock },
+ { key: 'link', icon: 'link', tooltip: t('manualEditor.toolbar.link'), action: insertLink },
+ { key: 'image', icon: 'image', tooltip: t('manualEditor.toolbar.image'), action: insertImage },
+ { key: 'table', icon: 'table', tooltip: t('manualEditor.toolbar.table'), action: insertTable },
+ { key: 'hr', icon: 'component-divider-horizontal', tooltip: t('manualEditor.toolbar.horizontalRule'), action: insertHorizontalRule },
],
},
-]
+])
const isPreviewMode = computed(() => activeTab.value === 'preview')
const viewToggleIcon = computed(() => (isPreviewMode.value ? 'edit' : 'view-module'))
-const viewToggleTooltip = computed(() => (isPreviewMode.value ? '切换到编辑视图' : '切换到预览视图'))
-const viewToggleLabel = computed(() => (isPreviewMode.value ? '返回编辑' : '预览内容'))
+const viewToggleTooltip = computed(() =>
+ isPreviewMode.value
+ ? t('manualEditor.view.toggleToEdit')
+ : t('manualEditor.view.toggleToPreview'),
+)
+const viewToggleLabel = computed(() =>
+ isPreviewMode.value ? t('manualEditor.view.editLabel') : t('manualEditor.view.previewLabel'),
+)
const handleToolbarAction = (action: ToolbarAction) => {
if (saving.value) {
@@ -374,7 +383,9 @@ marked.use({
})
const previewHTML = computed(() => {
- if (!form.content) return '<p class="empty-preview">暂无内容</p>'
+ if (!form.content) {
+ return `<p class="empty-preview">${t('manualEditor.preview.empty')}</p>`
+ }
const safeMarkdown = safeMarkdownToHTML(form.content)
const html = marked.parse(safeMarkdown)
return sanitizeHTML(html)
@@ -382,12 +393,13 @@ const previewHTML = computed(() => {
const kbDisabled = computed(() => mode.value === 'edit' && !!form.kbId)
-const dialogTitle = computed(() => {
- if (mode.value === 'edit') {
- return '编辑 Markdown 知识'
- }
- return '在线编辑 Markdown 知识'
-})
+const dialogTitle = computed(() =>
+ mode.value === 'edit' ? t('manualEditor.title.edit') : t('manualEditor.title.create'),
+)
+
+const lastUpdatedText = computed(() =>
+ lastUpdatedAt.value ? t('manualEditor.status.lastUpdated', { time: lastUpdatedAt.value }) : '',
+)
const loadKnowledgeBases = async () => {
kbLoading.value = true
@@ -403,7 +415,10 @@ const loadKnowledgeBases = async () => {
if (presetKbId) {
const exists = list.find((item) => item.value === presetKbId)
if (!exists) {
- kbOptions.value.unshift({ label: '当前知识库', value: presetKbId })
+ kbOptions.value.unshift({
+ label: t('manualEditor.labels.currentKnowledgeBase'),
+ value: presetKbId,
+ })
}
form.kbId = presetKbId
} else {
@@ -411,7 +426,7 @@ const loadKnowledgeBases = async () => {
}
}
} catch (error) {
- console.error('加载知识库列表失败:', error)
+ console.error('[ManualEditor] Failed to load knowledge base list:', error)
kbOptions.value = []
} finally {
kbLoading.value = false
@@ -438,7 +453,7 @@ const parseManualMetadata = (
}
}
} catch (error) {
- console.warn('解析手工知识元数据失败:', error)
+ console.warn('[ManualEditor] Failed to parse manual metadata:', error)
}
return null
}
@@ -452,7 +467,7 @@ const loadKnowledgeContent = async () => {
const res: any = await getKnowledgeDetails(knowledgeId.value)
const data: KnowledgeDetailResponse | undefined = res?.data
if (!data) {
- MessagePlugin.error('获取知识详情失败')
+ MessagePlugin.error(t('manualEditor.error.fetchDetailFailed'))
return
}
@@ -470,11 +485,14 @@ const loadKnowledgeContent = async () => {
}
if (form.kbId && !kbOptions.value.find((item) => item.value === form.kbId)) {
- kbOptions.value.unshift({ label: '当前知识库', value: form.kbId })
+ kbOptions.value.unshift({
+ label: t('manualEditor.labels.currentKnowledgeBase'),
+ value: form.kbId,
+ })
}
} catch (error) {
- console.error('加载手工知识失败:', error)
- MessagePlugin.error('获取知识详情失败')
+ console.error('[ManualEditor] Failed to load manual knowledge:', error)
+ MessagePlugin.error(t('manualEditor.error.fetchDetailFailed'))
} finally {
contentLoading.value = false
}
@@ -496,7 +514,7 @@ const generateDefaultTitle = () => {
if (uiStore.manualEditorInitialTitle) {
return uiStore.manualEditorInitialTitle
}
- return `新建文档-${new Date().toLocaleString()}`
+ return `${t('manualEditor.defaultTitlePrefix')}-${new Date().toLocaleString()}`
}
const initialize = async () => {
@@ -521,19 +539,19 @@ const initialize = async () => {
const validateForm = (targetStatus: ManualStatus): boolean => {
if (!form.kbId) {
- MessagePlugin.warning('请选择目标知识库')
+ MessagePlugin.warning(t('manualEditor.warning.selectKnowledgeBase'))
return false
}
if (!form.title || !form.title.trim()) {
- MessagePlugin.warning('请输入知识标题')
+ MessagePlugin.warning(t('manualEditor.warning.enterTitle'))
return false
}
if (!form.content || !form.content.trim()) {
- MessagePlugin.warning('请输入知识内容')
+ MessagePlugin.warning(t('manualEditor.warning.enterContent'))
return false
}
if (targetStatus === 'publish' && form.content.trim().length < 10) {
- MessagePlugin.warning('内容过短,建议补充更多信息后再发布')
+ MessagePlugin.warning(t('manualEditor.warning.contentTooShort'))
return false
}
return true
@@ -564,7 +582,11 @@ const handleSave = async (targetStatus: ManualStatus) => {
}
if (response?.success) {
- MessagePlugin.success(targetStatus === 'draft' ? '草稿已保存' : '知识已发布并开始索引')
+ MessagePlugin.success(
+ targetStatus === 'draft'
+ ? t('manualEditor.success.draftSaved')
+ : t('manualEditor.success.published'),
+ )
if (knowledgeID) {
uiStore.notifyManualEditorSuccess({
kbId,
@@ -574,11 +596,11 @@ const handleSave = async (targetStatus: ManualStatus) => {
}
uiStore.closeManualEditor()
} else {
- const message = response?.message || '保存失败,请稍后重试'
+ const message = response?.message || t('manualEditor.error.saveFailed')
MessagePlugin.error(message)
}
} catch (error: any) {
- const message = error?.error?.message || error?.message || '保存失败,请稍后重试'
+ const message = error?.error?.message || error?.message || t('manualEditor.error.saveFailed')
MessagePlugin.error(message)
} finally {
saving.value = false
@@ -630,31 +652,31 @@ onBeforeUnmount(() => {
>
<div class="editor-body" v-if="initialLoaded">
<div class="form-row">
- <label class="form-label">目标知识库</label>
+ <label class="form-label">{{ $t('manualEditor.form.knowledgeBaseLabel') }}</label>
<t-select
v-model="form.kbId"
:disabled="kbDisabled"
:loading="kbLoading"
:options="kbOptions"
- placeholder="请选择知识库"
+ :placeholder="$t('manualEditor.form.knowledgeBasePlaceholder')"
:popup-props="{ overlayStyle: { zIndex: 2200 } }"
/>
</div>
<div class="form-row">
- <label class="form-label">知识标题</label>
+ <label class="form-label">{{ $t('manualEditor.form.titleLabel') }}</label>
<t-input
v-model="form.title"
maxlength="100"
- placeholder="请输入标题"
+ :placeholder="$t('manualEditor.form.titlePlaceholder')"
showLimitNumber
/>
</div>
<div class="status-row" v-if="mode === 'edit'">
- <t-tag theme="warning" v-if="form.status === 'draft'">当前状态:草稿</t-tag>
- <t-tag theme="success" v-else>当前状态:已发布</t-tag>
- <span v-if="lastUpdatedAt" class="status-timestamp">最近更新:{{ lastUpdatedAt }}</span>
+ <t-tag theme="warning" v-if="form.status === 'draft'">{{ $t('manualEditor.status.draftTag') }}</t-tag>
+ <t-tag theme="success" v-else>{{ $t('manualEditor.status.publishedTag') }}</t-tag>
+ <span v-if="lastUpdatedText" class="status-timestamp">{{ lastUpdatedText }}</span>
</div>
<div class="editor-toolbar">
@@ -687,11 +709,11 @@ onBeforeUnmount(() => {
ref="textareaComponent"
v-if="!contentLoading"
v-model="form.content"
- placeholder="支持 Markdown 语法,可使用 # 标题、列表、代码块等"
+ :placeholder="$t('manualEditor.form.contentPlaceholder')"
:autosize="{ minRows: 16, maxRows: 24 }"
/>
<div v-else class="loading-placeholder">
- <t-loading size="small" text="正在加载内容" />
+ <t-loading size="small" :text="$t('manualEditor.loading.content')" />
</div>
</div>
<div class="editor-pane" v-show="activeTab === 'preview'">
@@ -701,7 +723,9 @@ onBeforeUnmount(() => {
<div class="dialog-footer">
<div class="footer-left">
- <t-button variant="outline" theme="default" @click="handleClose">取消</t-button>
+ <t-button variant="outline" theme="default" @click="handleClose">
+ {{ $t('manualEditor.actions.cancel') }}
+ </t-button>
</div>
<div class="footer-right">
<t-tooltip :content="viewToggleTooltip" placement="top">
@@ -722,20 +746,20 @@ onBeforeUnmount(() => {
@click="handleSave('draft')"
:loading="saving && savingAction === 'draft'"
>
- 暂存草稿
+ {{ $t('manualEditor.actions.saveDraft') }}
</t-button>
<t-button
theme="primary"
@click="handleSave('publish')"
:loading="saving && savingAction === 'publish'"
>
- 发布入库
+ {{ $t('manualEditor.actions.publish') }}
</t-button>
</div>
</div>
</div>
<div v-else class="loading-wrapper">
- <t-loading size="medium" text="正在准备编辑器" />
+ <t-loading size="medium" :text="$t('manualEditor.loading.preparing')" />
</div>
</t-dialog>
</template>
diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue
index 34841d52c..ab84722d2 100644
--- a/frontend/src/components/menu.vue
+++ b/frontend/src/components/menu.vue
@@ -65,7 +65,7 @@
{{ subitem.title }}
</span>
<t-dropdown
- :options="[{ content: '删除记录', value: 'delete' }]"
+ :options="[{ content: t('upload.deleteRecord'), value: 'delete' }]"
@click="(data) => data.value === 'delete' && delCard(subitem.originalIndex, subitem)"
placement="bottom-right"
trigger="click">
@@ -104,6 +104,9 @@ import { useAuthStore } from '@/stores/auth';
import { useUIStore } from '@/stores/ui';
import { MessagePlugin } from "tdesign-vue-next";
import UserMenu from '@/components/UserMenu.vue';
+import { useI18n } from 'vue-i18n';
+
+const { t } = useI18n();
let uploadInput = ref();
const usemenuStore = useMenuStore();
const authStore = useAuthStore();
@@ -195,7 +198,7 @@ const initializedKnowledgeBases = computed(() => {
// 时间分组函数
const getTimeCategory = (dateStr: string): string => {
- if (!dateStr) return '更早';
+ if (!dateStr) return t('time.earlier');
const date = new Date(dateStr);
const now = new Date();
@@ -208,17 +211,17 @@ const getTimeCategory = (dateStr: string): string => {
const sessionDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
if (sessionDate.getTime() >= today.getTime()) {
- return '今天';
+ return t('time.today');
} else if (sessionDate.getTime() >= yesterday.getTime()) {
- return '昨天';
+ return t('time.yesterday');
} else if (date.getTime() >= sevenDaysAgo.getTime()) {
- return '近7天';
+ return t('time.last7Days');
} else if (date.getTime() >= thirtyDaysAgo.getTime()) {
- return '近30天';
+ return t('time.last30Days');
} else if (date.getTime() >= oneYearAgo.getTime()) {
- return '近1年';
+ return t('time.lastYear');
} else {
- return '更早';
+ return t('time.earlier');
}
};
@@ -230,12 +233,12 @@ const groupedSessions = computed(() => {
}
const groups: { [key: string]: any[] } = {
- '今天': [],
- '昨天': [],
- '近7天': [],
- '近30天': [],
- '近1年': [],
- '更早': []
+ [t('time.today')]: [],
+ [t('time.yesterday')]: [],
+ [t('time.last7Days')]: [],
+ [t('time.last30Days')]: [],
+ [t('time.lastYear')]: [],
+ [t('time.earlier')]: []
};
// 将sessions按时间分组
@@ -248,7 +251,7 @@ const groupedSessions = computed(() => {
});
// 按顺序返回非空分组
- const orderedLabels = ['今天', '昨天', '近7天', '近30天', '近1年', '更早'];
+ const orderedLabels = [t('time.today'), t('time.yesterday'), t('time.last7Days'), t('time.last30Days'), t('time.lastYear'), t('time.earlier')];
return orderedLabels
.filter(label => groups[label].length > 0)
.map(label => ({
@@ -267,10 +270,10 @@ const kbMenuItem = computed(() => {
})
const loading = ref(false)
-const uploadActionOptions = [
- { content: '上传文档', value: 'upload' },
- { content: '在线编辑', value: 'manual' },
-]
+const uploadActionOptions = computed(() => [
+ { content: t('upload.uploadDocument'), value: 'upload' },
+ { content: t('upload.onlineEdit'), value: 'manual' },
+])
const uploadFile = async () => {
// 获取当前知识库ID
const currentKbId = await getCurrentKbId();
@@ -284,12 +287,12 @@ const uploadFile = async () => {
// 检查知识库是否已初始化(有 EmbeddingModelID 和 SummaryModelID)
if (!kb.embedding_model_id || kb.embedding_model_id === '' ||
!kb.summary_model_id || kb.summary_model_id === '') {
- MessagePlugin.warning("该知识库尚未完成初始化配置,请先前往设置页面配置模型信息后再上传文件");
+ MessagePlugin.warning(t('knowledgeBase.notInitialized'));
return;
}
} catch (error) {
console.error('获取知识库信息失败:', error);
- MessagePlugin.error("获取知识库信息失败,无法上传文件");
+ MessagePlugin.error(t('knowledgeBase.getInfoFailed'));
return;
}
}
diff --git a/frontend/src/components/upload-mask.vue b/frontend/src/components/upload-mask.vue
index a718120ca..fac5eb2fc 100644
--- a/frontend/src/components/upload-mask.vue
+++ b/frontend/src/components/upload-mask.vue
@@ -1,11 +1,13 @@
<script setup lang="ts">
+import { useI18n } from 'vue-i18n'
+const { t } = useI18n()
</script>
<template>
<div class="mask">
<img class="upload-mask-img" src="@/assets/img/upload-mask.svg" alt="">
- <span class="drag-txt">将文件拖放到此处</span>
- <span class="drag-type-txt">pdf、doc 格式文件,不超过30M</span>
- <span class="drag-type-txt">text、markdown格式文件,不超过30M</span>
+ <span class="drag-txt">{{ $t('file.upload') }}</span>
+ <span class="drag-type-txt">{{ $t('knowledgeBase.pdfDocFormat') }}</span>
+ <span class="drag-type-txt">{{ $t('knowledgeBase.textMarkdownFormat') }}</span>
</div>
</template>
<style scoped lang="less">
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index dea113ced..e332bee14 100644
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -15,6 +15,7 @@ export default {
knowledgeBase: {
title: 'Knowledge Base',
list: 'Knowledge Base List',
+ fileContent: 'File Content',
detail: 'Knowledge Base Details',
create: 'Create Knowledge Base',
edit: 'Edit Knowledge Base',
@@ -67,6 +68,10 @@ export default {
totalSize: 'Total size',
// Additional translations for KnowledgeBase.vue
newSession: 'New Chat',
+ editDocument: 'Edit Document',
+ draft: 'Draft',
+ draftTip: 'Temporarily saved and not included in retrieval',
+ untitledDocument: 'Untitled Document',
deleteDocument: 'Delete Document',
parsingFailed: 'Parsing failed',
parsingInProgress: 'Parsing...',
@@ -107,39 +112,31 @@ export default {
emptyKnowledgeDragDrop: 'Knowledge is empty, drag and drop to upload',
pdfDocFormat: 'pdf, doc format files, max 10M',
textMarkdownFormat: 'text, markdown format files, max 200K',
- dragFileNotText: 'Please drag files instead of text or links'
+ dragFileNotText: 'Please drag files instead of text or links',
+ searchPlaceholder: 'Search knowledge bases...',
+ noMatch: 'No matching knowledge base found',
+ noKnowledge: 'No knowledge bases available',
+ loadingFailed: 'Failed to load knowledge bases'
},
- chat: {
- title: 'Chat',
- newChat: 'New Chat',
- inputPlaceholder: 'Enter your message...',
- send: 'Send',
- thinking: 'Thinking...',
- regenerate: 'Regenerate',
+
+ agent: {
+ taskLabel: 'Task:',
copy: 'Copy',
- delete: 'Delete',
- reference: 'Reference',
- noMessages: 'No messages',
- // Additional translations for chat components
- waitingForAnswer: 'Waiting for answer...',
- cannotAnswer: 'Sorry, I cannot answer this question.',
- summarizingAnswer: 'Summarizing answer...',
- loading: 'Loading...',
- enterDescription: 'Enter description',
- referencedContent: '{count} related materials used',
- deepThinking: 'Deep thinking completed',
- knowledgeBaseQandA: 'Knowledge Base Q&A',
- askKnowledgeBase: 'Ask the knowledge base',
- sourcesCount: '{count} sources',
- pleaseEnterContent: 'Please enter content!',
- pleaseUploadKnowledgeBase: 'Please upload knowledge base first!',
- replyingPleaseWait: 'Replying, please try again later!',
- createSessionFailed: 'Failed to create session',
- createSessionError: 'Session creation error',
- unableToGetKnowledgeBaseId: 'Unable to get knowledge base ID'
+ addToKnowledgeBase: 'Add to Knowledge Base',
+ updatePlan: 'Update Plan',
+ webSearchFound: 'Found <strong>{count}</strong> web search result(s)',
+ argumentsLabel: 'Arguments',
+ toolFallback: 'Tool'
},
settings: {
title: 'Settings',
+ modelConfig: 'Model Settings',
+ agentConfig: 'Agent Settings',
+ webSearchConfig: 'Web Search',
+ mcpService: 'MCP Service',
+ systemSettings: 'System Settings',
+ tenantInfo: 'Tenant Info',
+ apiInfo: 'API Info',
system: 'System Settings',
systemConfig: 'System Configuration',
knowledgeBaseSettings: 'Knowledge Base Settings',
@@ -178,6 +175,35 @@ export default {
saveFailedSettings: 'Failed to save settings',
enterNameRequired: 'Enter name'
},
+ webSearchSettings: {
+ title: 'Web Search Configuration',
+ description: 'Configure web search so answers can include up-to-date information from the internet.',
+ providerLabel: 'Search Provider',
+ providerDescription: 'Choose the search engine service used for web search',
+ providerPlaceholder: 'Select a search engine...',
+ apiKeyLabel: 'API Key',
+ apiKeyDescription: 'Enter the API key for the selected search provider',
+ apiKeyPlaceholder: 'Enter API key',
+ maxResultsLabel: 'Maximum Results',
+ maxResultsDescription: 'Maximum number of results returned per search (1-50)',
+ includeDateLabel: 'Include Publish Date',
+ includeDateDescription: 'Include publish date information in search results',
+ compressionLabel: 'Compression Method',
+ compressionDescription: 'Choose how to compress content from search results',
+ compressionNone: 'No Compression',
+ compressionSummary: 'LLM Summary',
+ blacklistLabel: 'URL Blacklist',
+ blacklistDescription: 'Exclude specific domains or URLs from search results. One per line. Supports wildcards (*) and regular expressions (/pattern/).',
+ blacklistPlaceholder: 'For example:\n*://*.example.com/*\n/example\\.(net|org)/',
+ errors: {
+ unknown: 'Unknown error'
+ },
+ toasts: {
+ loadProvidersFailed: 'Failed to load search providers: {message}',
+ saveSuccess: 'Web search configuration saved',
+ saveFailed: 'Failed to save configuration: {message}'
+ }
+ },
initialization: {
title: 'Initialization',
welcome: 'Welcome to WeKnora',
@@ -431,12 +457,21 @@ export default {
registerError: 'Registration error, please try again later',
forgotPasswordNotAvailable: 'Password recovery function is temporarily unavailable, please contact administrator'
},
+ authStore: {
+ errors: {
+ parseUserFailed: 'Failed to parse user information',
+ parseTenantFailed: 'Failed to parse tenant information',
+ parseKnowledgeBasesFailed: 'Failed to parse knowledge base list',
+ parseCurrentKnowledgeBaseFailed: 'Failed to parse current knowledge base'
+ }
+ },
common: {
confirm: 'Confirm',
cancel: 'Cancel',
save: 'Save',
delete: 'Delete',
edit: 'Edit',
+ default: 'Default',
create: 'Create',
search: 'Search',
filter: 'Filter',
@@ -451,6 +486,7 @@ export default {
success: 'Success',
warning: 'Warning',
info: 'Information',
+ selectAll: 'Select All',
yes: 'Yes',
no: 'No',
ok: 'OK',
@@ -460,7 +496,12 @@ export default {
finish: 'Finish',
all: 'All',
reset: 'Reset',
- clear: 'Clear'
+ clear: 'Clear',
+ website: 'Official Website',
+ on: 'On',
+ off: 'Off',
+ resetToDefault: 'Reset to default',
+ confirmDelete: 'Confirm Delete'
},
file: {
upload: 'Upload File',
@@ -475,8 +516,388 @@ export default {
maxSizeExceeded: 'Maximum file size exceeded',
selectFile: 'Select File'
},
+ manualEditor: {
+ placeholders: {
+ heading: 'Heading {level}',
+ listItem: 'List item',
+ taskItem: 'Task item',
+ quote: 'Quoted text',
+ code: 'Code content',
+ linkText: 'Link text',
+ imageAlt: 'Description',
+ bold: 'Bold text',
+ italic: 'Italic text',
+ strike: 'Strikethrough',
+ inlineCode: 'code'
+ },
+ table: {
+ column1: 'Column 1',
+ column2: 'Column 2',
+ cell: 'Content'
+ },
+ toolbar: {
+ bold: 'Bold',
+ italic: 'Italic',
+ strike: 'Strikethrough',
+ inlineCode: 'Inline code',
+ heading1: 'Heading 1',
+ heading2: 'Heading 2',
+ heading3: 'Heading 3',
+ bulletList: 'Bullet list',
+ orderedList: 'Numbered list',
+ taskList: 'Task list',
+ blockquote: 'Blockquote',
+ codeBlock: 'Code block',
+ link: 'Insert link',
+ image: 'Insert image',
+ table: 'Insert table',
+ horizontalRule: 'Horizontal rule'
+ },
+ view: {
+ toggleToEdit: 'Switch to edit view',
+ toggleToPreview: 'Switch to preview view',
+ editLabel: 'Back to edit',
+ previewLabel: 'Preview content'
+ },
+ preview: {
+ empty: 'No content yet'
+ },
+ title: {
+ edit: 'Edit Markdown Knowledge',
+ create: 'Create Markdown Knowledge'
+ },
+ labels: {
+ currentKnowledgeBase: 'Current knowledge base'
+ },
+ defaultTitlePrefix: 'New Document',
+ error: {
+ fetchDetailFailed: 'Failed to fetch knowledge details',
+ saveFailed: 'Save failed, please try again later'
+ },
+ warning: {
+ selectKnowledgeBase: 'Please select a target knowledge base',
+ enterTitle: 'Please enter a knowledge title',
+ enterContent: 'Please enter knowledge content',
+ contentTooShort: 'Content is too short. Please add more information before publishing'
+ },
+ success: {
+ draftSaved: 'Draft saved',
+ published: 'Knowledge published and indexing started'
+ },
+ form: {
+ knowledgeBaseLabel: 'Target knowledge base',
+ knowledgeBasePlaceholder: 'Select knowledge base',
+ titleLabel: 'Knowledge title',
+ titlePlaceholder: 'Enter title',
+ contentPlaceholder: 'Supports Markdown. Use # headings, lists, code blocks, etc.'
+ },
+ status: {
+ draftTag: 'Status: Draft',
+ publishedTag: 'Status: Published',
+ lastUpdated: 'Last updated: {time}'
+ },
+ loading: {
+ content: 'Loading content...',
+ preparing: 'Preparing editor...'
+ },
+ actions: {
+ cancel: 'Cancel',
+ saveDraft: 'Save Draft',
+ publish: 'Publish'
+ }
+ },
+ input: {
+ placeholder: 'Ask questions based on the knowledge base',
+ agentMode: 'Agent Mode',
+ normalMode: 'Normal Mode',
+ normalModeDesc: 'Knowledge base RAG Q&A',
+ agentModeDesc: 'ReAct reasoning framework with multi-step thinking',
+ agentNotReadyTooltip: 'Agent is not ready. Please finish configuration first.',
+ agentNotReadyDetail: 'Agent is not ready. Please complete the agent configuration in settings (thinking model, rerank model, and allowed tools).',
+ goToSettings: 'Go to settings →',
+ webSearch: {
+ toggleOn: 'Enable Web Search',
+ toggleOff: 'Disable Web Search',
+ notConfigured: 'Web search engine not configured'
+ },
+ knowledgeBase: 'Knowledge Base',
+ knowledgeBaseWithCount: 'Knowledge Base ({count})',
+ notConfigured: 'Not configured',
+ model: 'Model',
+ remote: 'Remote',
+ noModel: 'No available models',
+ stopGeneration: 'Stop Generation',
+ send: 'Send',
+ thinkingLabel: 'Thinking:',
+ messages: {
+ enterContent: 'Please enter content first!',
+ selectKnowledge: 'Please select a knowledge base first!',
+ replying: 'Currently replying, please try again later!',
+ agentSwitchedOn: 'Switched to Agent Mode',
+ agentSwitchedOff: 'Switched to Normal Mode',
+ agentEnabled: 'Agent Mode enabled',
+ agentDisabled: 'Agent Mode disabled',
+ agentNotReadyDetail: 'Agent is not ready. Please complete the agent configuration in settings (thinking model, rerank model, and allowed tools).',
+ webSearchNotConfigured: 'Web search engine is not configured. Please configure a provider and credentials in settings.',
+ webSearchEnabled: 'Web search enabled',
+ webSearchDisabled: 'Web search disabled',
+ sessionMissing: 'Session ID does not exist',
+ messageMissing: 'Unable to get message ID. Please refresh the page and try again.',
+ stopSuccess: 'Generation stopped',
+ stopFailed: 'Failed to stop. Please try again.'
+ }
+ },
+ createChat: {
+ title: 'Knowledge-base Q&A - AI Assistant',
+ newSessionTitle: 'New Session',
+ messages: {
+ selectKnowledgeBase: 'Please select a knowledge base first',
+ createFailed: 'Failed to create session',
+ createError: 'Failed to create session, please try again later'
+ }
+ },
+ knowledgeList: {
+ create: 'Create Knowledge Base',
+ uninitializedBanner: 'Some knowledge bases are not initialized. Configure model information in settings before adding documents.',
+ empty: {
+ title: 'No knowledge bases yet',
+ description: 'Click “Create Knowledge Base” in the top-right corner to add your first one.'
+ },
+ delete: {
+ confirmTitle: 'Delete Confirmation',
+ confirmMessage: 'Are you sure you want to delete the knowledge base “{name}”? This action cannot be undone.',
+ confirmButton: 'Delete'
+ },
+ messages: {
+ deleted: 'Knowledge base deleted',
+ deleteFailed: 'Failed to delete knowledge base'
+ }
+ },
+ knowledgeEditor: {
+ titleCreate: 'Create Knowledge Base',
+ titleEdit: 'Knowledge Base Settings',
+ sidebar: {
+ basic: 'Basic Information',
+ models: 'Model Configuration',
+ chunking: 'Chunking Settings',
+ advanced: 'Advanced Settings'
+ },
+ basic: {
+ title: 'Basic Information',
+ description: 'Configure the knowledge base name and description',
+ nameLabel: 'Knowledge Base Name',
+ namePlaceholder: 'Enter knowledge base name',
+ descriptionLabel: 'Knowledge Base Description',
+ descriptionPlaceholder: 'Enter knowledge base description (optional)'
+ },
+ buttons: {
+ create: 'Create Knowledge Base',
+ save: 'Save Configuration'
+ },
+ messages: {
+ loadModelsFailed: 'Failed to load model list',
+ loadDataFailed: 'Failed to load knowledge base data',
+ notFound: 'Knowledge base not found',
+ nameRequired: 'Please enter the knowledge base name',
+ embeddingRequired: 'Please select an embedding model',
+ summaryRequired: 'Please select a summary model',
+ multimodalInvalid: 'Multimodal configuration validation failed',
+ createSuccess: 'Knowledge base created successfully',
+ createFailed: 'Failed to create knowledge base',
+ missingId: 'Knowledge base ID is missing',
+ buildDataFailed: 'Failed to construct submission data',
+ updateSuccess: 'Configuration saved successfully'
+ },
+ models: {
+ title: 'Model Configuration',
+ description: 'Select appropriate AI models for the knowledge base',
+ llmLabel: 'LLM Model',
+ llmDesc: 'Large language model used for conversations and Q&A',
+ llmPlaceholder: 'Select an LLM model',
+ embeddingLabel: 'Embedding Model',
+ embeddingDesc: 'Embedding model used for text vectorization',
+ embeddingPlaceholder: 'Select an embedding model',
+ embeddingLocked: 'Knowledge base already has files. Embedding model cannot be modified',
+ rerankLabel: 'ReRank Model',
+ rerankDesc: 'Model for re-ranking search results (optional)',
+ rerankPlaceholder: 'Select a ReRank model (optional)'
+ },
+ chunking: {
+ title: 'Chunking Settings',
+ description: 'Configure document chunking parameters to improve retrieval quality',
+ sizeLabel: 'Chunk Size',
+ sizeDescription: 'Controls the number of characters in each chunk (100-4000)',
+ characters: 'characters',
+ overlapLabel: 'Chunk Overlap',
+ overlapDescription: 'Number of overlapping characters between adjacent chunks (0-500)',
+ separatorsLabel: 'Separators',
+ separatorsDescription: 'Separators used when chunking documents',
+ separatorsPlaceholder: 'Select separators',
+ separators: {
+ doubleNewline: 'Double newline (\\n\\n)',
+ singleNewline: 'Single newline (\\n)',
+ periodCn: 'Chinese period (。)',
+ exclamationCn: 'Exclamation mark (!)',
+ questionCn: 'Question mark (?)',
+ semicolonCn: 'Chinese semicolon (;)',
+ semicolonEn: 'Semicolon (;)',
+ space: 'Space ( )'
+ }
+ },
+ advanced: {
+ title: 'Advanced Settings',
+ description: 'Configure multimodal and knowledge graph features',
+ multimodal: {
+ label: 'Multimodal Feature',
+ description: 'Enable understanding of multimodal content such as images and videos',
+ vllmLabel: 'VLLM Vision Model',
+ vllmDescription: 'Vision-language model required for multimodal understanding',
+ vllmPlaceholder: 'Select a VLLM model (required)',
+ storageTitle: 'Storage Configuration',
+ storageTypeLabel: 'Storage Type',
+ storageTypeDescription: 'Choose the storage solution for multimodal files (MinIO or Tencent Cloud COS)',
+ storageTypeOptions: {
+ minio: 'MinIO',
+ cos: 'Tencent Cloud COS'
+ },
+ minio: {
+ bucketLabel: 'Bucket Name',
+ bucketDescription: 'Name of the MinIO bucket (required)',
+ bucketPlaceholder: 'Enter bucket name (required)',
+ useSslLabel: 'Use SSL',
+ useSslDescription: 'Whether to use SSL connection',
+ pathPrefixLabel: 'Path Prefix',
+ pathPrefixDescription: 'Optional prefix for stored file paths',
+ pathPrefixPlaceholder: 'Enter path prefix'
+ },
+ cos: {
+ secretIdLabel: 'SecretId',
+ secretIdDescription: 'Tencent Cloud API secret ID (required)',
+ secretIdPlaceholder: 'Enter SecretId (required)',
+ secretKeyLabel: 'SecretKey',
+ secretKeyDescription: 'Tencent Cloud API secret key (required)',
+ secretKeyPlaceholder: 'Enter SecretKey (required)',
+ regionLabel: 'Region',
+ regionDescription: 'Region where the COS bucket is located (required)',
+ regionPlaceholder: 'e.g. ap-guangzhou (required)',
+ bucketLabel: 'Bucket Name',
+ bucketDescription: 'COS bucket name (required)',
+ bucketPlaceholder: 'Enter bucket name (required)',
+ appIdLabel: 'AppId',
+ appIdDescription: 'Tencent Cloud application ID (required)',
+ appIdPlaceholder: 'Enter AppId (required)',
+ pathPrefixLabel: 'Path Prefix',
+ pathPrefixDescription: 'Optional prefix for stored file paths',
+ pathPrefixPlaceholder: 'Enter path prefix'
+ }
+ },
+ graph: {
+ label: 'Knowledge Graph Extraction',
+ description: 'Automatically extract entities and relationships to build a knowledge graph',
+ configTitle: 'Graph Configuration',
+ promptLabel: 'Prompt Text',
+ promptDescription: 'Prompt used to guide the model when extracting entities and relationships',
+ promptPlaceholder: 'Enter prompt text',
+ tagsLabel: 'Tags',
+ tagsDescription: 'Predefined entity tags (separate multiple tags with commas)',
+ tagsPlaceholder: 'Enter a tag and press Enter'
+ }
+ }
+ },
+ chat: {
+ title: 'Chat',
+ newChat: 'New Chat',
+ inputPlaceholder: 'Enter your message...',
+ send: 'Send',
+ thinking: 'Thinking...',
+ regenerate: 'Regenerate',
+ copy: 'Copy',
+ delete: 'Delete',
+ reference: 'Reference',
+ noMessages: 'No messages',
+ // Additional translations for chat components
+ waitingForAnswer: 'Waiting for answer...',
+ cannotAnswer: 'Sorry, I cannot answer this question.',
+ summarizingAnswer: 'Summarizing answer...',
+ loading: 'Loading...',
+ referencedContent: '{count} related materials used',
+ deepThinking: 'Deep thinking completed',
+ knowledgeBaseQandA: 'Knowledge Base Q&A',
+ askKnowledgeBase: 'Ask the knowledge base',
+ sourcesCount: '{count} sources',
+ pleaseEnterContent: 'Please enter content!',
+ pleaseUploadKnowledgeBase: 'Please upload knowledge base first!',
+ replyingPleaseWait: 'Replying, please try again later!',
+ createSessionFailed: 'Failed to create session',
+ createSessionError: 'Session creation error',
+ unableToGetKnowledgeBaseId: 'Unable to get knowledge base ID',
+ summaryInProgress: 'Summarizing answer…',
+ thinkingAlt: 'Thinking in progress',
+ deepThoughtCompleted: 'Deep thinking completed',
+ deepThoughtAlt: 'Deep thinking finished',
+ referencesTitle: 'Referenced {count} related item(s)',
+ referenceIconAlt: 'Reference materials icon',
+ chunkIdLabel: 'Chunk ID:',
+ documentIdLabel: 'Document ID:',
+ noPlanSteps: 'No detailed steps provided',
+ chunkIndexLabel: 'Chunk #{index}',
+ chunkPositionLabel: '(Position: {position})',
+ noRelatedChunks: 'No related chunks found',
+ noSearchResults: 'No search results found',
+ relevanceHigh: 'High relevance',
+ relevanceMedium: 'Medium relevance',
+ relevanceLow: 'Low relevance',
+ relevanceWeak: 'Weak relevance',
+ webSearchNoResults: 'No web search results found',
+ otherSource: 'Other sources',
+ webGroupIntro: 'The following {count} items are from',
+ graphConfigTitle: 'Graph Configuration',
+ entityTypesLabel: 'Entity types:',
+ relationTypesLabel: 'Relation types:',
+ graphResultsHeader: '{count} related results found',
+ graphNoResults: 'No related graph information found',
+ unknownLink: 'Unknown link',
+ contentLengthLabel: 'Length {value}',
+ notProvided: 'Not provided',
+ promptLabel: 'Prompt',
+ errorMessageLabel: 'Error message',
+ summaryLabel: 'Summary',
+ rawTextLabel: 'Raw text',
+ collapseRaw: 'Collapse original',
+ expandRaw: 'Expand original',
+ noWebContent: 'No web content fetched',
+ lengthChars: '{value} characters',
+ lengthThousands: '{value}k characters',
+ lengthTenThousands: '{value} ten-thousand characters',
+ sqlQueryExecuted: 'Executed SQL query:',
+ sqlResultsLabel: 'Results:',
+ rowsLabel: 'rows',
+ columnsLabel: 'columns',
+ noDatabaseRecords: 'No matching records found',
+ nullValuePlaceholder: '<NULL>',
+ documentTitleLabel: 'Document title:',
+ chunkCountLabel: 'Chunk count:',
+ chunkCountValue: 'At least {count}',
+ statusDescription: 'Status notes',
+ statusIndexed: 'Document is indexed and searchable',
+ statusSearchable: 'Search tools can locate document content',
+ statusChunkDetailAvailable: 'Use get_chunk_detail to view chunk details',
+ positionLabel: 'Position:',
+ chunkPositionValue: 'Chunk #{index}',
+ contentLengthLabelSimple: 'Content length:',
+ fullContentLabel: 'Full content',
+ copyContent: 'Copy content',
+ knowledgeBaseCount: '{count} knowledge bases',
+ noKnowledgeBases: 'No knowledge bases available',
+ enterDescription: 'Enter description',
+ rawOutputLabel: 'Raw output',
+ selectKnowledgeBaseWarning: 'Please select at least one knowledge base',
+ processError: 'Processing error'
+ },
tenant: {
title: 'Tenant Information',
+ sectionDescription: 'View detailed configuration for the tenant',
+ apiDocument: 'API Document',
name: 'Tenant Name',
id: 'Tenant ID',
createdAt: 'Created At',
@@ -515,11 +936,89 @@ export default {
useApiKey: 'Use your API Key to start development, view complete API documentation and code examples.',
viewApiDoc: 'View API Documentation',
loadingAccountInfo: 'Loading account information...',
+ loadingInfo: 'Loading information...',
loadFailed: 'Load failed',
retry: 'Retry',
apiKeyCopied: 'API Key copied to clipboard',
unknown: 'Unknown',
- formatError: 'Format error'
+ formatError: 'Format error',
+ details: {
+ idLabel: 'Tenant ID',
+ idDescription: 'Unique identifier of your tenant',
+ nameLabel: 'Tenant Name',
+ nameDescription: 'Name of your tenant',
+ descriptionLabel: 'Tenant Description',
+ descriptionDescription: 'Detailed description of the tenant',
+ businessLabel: 'Tenant Business',
+ businessDescription: 'Business domain that the tenant belongs to',
+ statusLabel: 'Tenant Status',
+ statusDescription: 'Current operational status of the tenant',
+ createdAtLabel: 'Tenant Creation Time',
+ createdAtDescription: 'Time when the tenant was created'
+ },
+ storage: {
+ quotaLabel: 'Storage Quota',
+ quotaDescription: 'Total storage capacity allocated to the tenant',
+ usedLabel: 'Used Storage',
+ usedDescription: 'Storage space that has been used',
+ usageLabel: 'Storage Usage',
+ usageDescription: 'Percentage of storage capacity used'
+ },
+ messages: {
+ fetchFailed: 'Failed to fetch tenant information',
+ networkError: 'Network error, please try again later'
+ },
+ api: {
+ title: 'API Information',
+ description: 'View and manage your API key',
+ keyLabel: 'API Key',
+ keyDescription: 'Secret used for API requests. Keep it safe.',
+ copyTitle: 'Copy API Key',
+ docLabel: 'API Documentation',
+ docDescription: 'View complete API documentation and examples,',
+ openDoc: 'Open documentation',
+ userSectionTitle: 'User Information',
+ userIdLabel: 'User ID',
+ userIdDescription: 'Your unique user identifier',
+ usernameLabel: 'Username',
+ usernameDescription: 'Your login username',
+ emailLabel: 'Email',
+ emailDescription: 'Your registered email address',
+ createdAtLabel: 'Registration Time',
+ createdAtDescription: 'Time when the account was created',
+ noKey: 'No API Key available',
+ copySuccess: 'API Key copied to clipboard',
+ copyFailed: 'Copy failed, please copy manually'
+ }
+ },
+ system: {
+ title: 'System Information',
+ sectionDescription: 'View system version information and user account configuration',
+ loadingInfo: 'Loading information...',
+ retry: 'Retry',
+ versionLabel: 'System Version',
+ versionDescription: 'Current version number of the system',
+ buildTimeLabel: 'Build Time',
+ buildTimeDescription: 'Time when the system was built',
+ goVersionLabel: 'Go Version',
+ goVersionDescription: 'Go language version used by the backend',
+ unknown: 'Unknown',
+ messages: {
+ fetchFailed: 'Failed to fetch system information',
+ networkError: 'Network error, please try again later'
+ }
+ },
+ mcp: {
+ testResult: {
+ title: 'Test Result: {name}',
+ connectionSuccess: 'Connection successful',
+ connectionFailed: 'Connection failed',
+ toolsTitle: 'Available tools',
+ resourcesTitle: 'Available resources',
+ descriptionLabel: 'Description',
+ schemaLabel: 'Parameter schema',
+ emptyDescription: 'This service did not provide tools or resources'
+ }
},
error: {
network: 'Network error',
@@ -548,6 +1047,358 @@ export default {
topP: 'Top P',
selectModel: 'Select Model',
customModel: 'Custom Model',
- builtinModel: 'Built-in Model'
+ builtinModel: 'Built-in Model',
+ defaultTag: 'Default',
+ addModelInSettings: 'Go to global settings to add models',
+ loadFailed: 'Failed to load model list',
+ selectModelPlaceholder: 'Select a model',
+ searchPlaceholder: 'Search models...',
+ editor: {
+ addTitle: 'Add Model',
+ editTitle: 'Edit Model',
+ sourceLabel: 'Model Source',
+ sourceLocal: 'Ollama (Local)',
+ sourceRemote: 'Remote API',
+ description: {
+ chat: 'Configure large language models for conversations',
+ embedding: 'Configure embedding models for text vectorization',
+ rerank: 'Configure models for result re-ranking',
+ vllm: 'Configure vision-language models for multimodal understanding',
+ default: 'Configure model information'
+ },
+ modelNamePlaceholder: {
+ local: 'e.g. llama2:latest',
+ remote: 'e.g. gpt-4, claude-3-opus',
+ localVllm: 'e.g. llava:latest',
+ remoteVllm: 'e.g. gpt-4-vision-preview'
+ },
+ baseUrlLabel: 'Base URL',
+ baseUrlPlaceholder: 'e.g. https://api.openai.com/v1',
+ baseUrlPlaceholderVllm: 'e.g. http://localhost:11434/v1',
+ apiKeyOptional: 'API Key (optional)',
+ apiKeyPlaceholder: 'Enter API Key',
+ connectionTest: 'Connection Test',
+ testing: 'Testing...',
+ testConnection: 'Test Connection',
+ searchPlaceholder: 'Search models...',
+ downloadLabel: 'Download: {keyword}',
+ refreshList: 'Refresh List',
+ dimensionLabel: 'Vector Dimension',
+ dimensionPlaceholder: 'e.g. 1536',
+ checkDimension: 'Detect Dimension',
+ dimensionDetected: 'Detection succeeded. Vector dimension: {value}',
+ dimensionFailed: 'Detection failed, please enter the dimension manually',
+ remoteDimensionDetected: 'Detected vector dimension: {value}',
+ dimensionHint: 'Model selected. Click “Detect Dimension” to fetch the vector dimension automatically.',
+ setAsDefault: 'Set as default model',
+ loadModelListFailed: 'Failed to load model list',
+ listRefreshed: 'List refreshed',
+ fillModelAndUrl: 'Please fill in the model identifier and Base URL first',
+ remoteBaseUrlRequired: 'Remote API type requires a Base URL',
+ unsupportedModelType: 'Unsupported model type',
+ connectionSuccess: 'Connection succeeded',
+ connectionFailed: 'Connection failed',
+ connectionConfigError: 'Connection failed, please check the configuration',
+ downloadStarted: 'Started downloading {name}',
+ downloadCompleted: '{name} downloaded successfully',
+ downloadFailed: 'Failed to download {name}',
+ downloadStartFailed: 'Failed to start download',
+ validation: {
+ modelNameRequired: 'Please enter the model name',
+ modelNameEmpty: 'Model name cannot be empty',
+ modelNameMax: 'Model name cannot exceed 100 characters',
+ baseUrlRequired: 'Please enter the Base URL',
+ baseUrlEmpty: 'Base URL cannot be empty',
+ baseUrlInvalid: 'Invalid Base URL, please enter a valid URL'
+ }
+ }
+ },
+ language: {
+ zhCN: '简体中文',
+ enUS: 'English',
+ ruRU: 'Русский',
+ selectLanguage: 'Select Language',
+ language: 'Language',
+ languageDescription: 'Select interface display language',
+ languageSaved: 'Language settings saved'
+ },
+ general: {
+ title: 'General Settings',
+ allSettings: 'All Settings',
+ description: 'Configure language, appearance and other basic options',
+ settings: 'Settings',
+ close: 'Close Settings'
+ },
+ platform: {
+ subtitle: 'Enterprise-level Intelligent Document Retrieval Framework',
+ description: 'Making complex document understanding and precise retrieval simple',
+ rag: 'RAG Enhanced Generation',
+ hybridSearch: 'Hybrid Search',
+ localDeploy: 'Local Deployment',
+ multimodalParsing: 'Multimodal Document Parsing',
+ hybridSearchEngine: 'Hybrid Search Engine',
+ ragQandA: 'RAG Intelligent Q&A',
+ independentTenant: 'Independent Tenant Space',
+ fullApiAccess: 'Full API Access',
+ knowledgeBaseManagement: 'Knowledge Base Management',
+ carousel: {
+ agenticRagTitle: 'Agentic RAG',
+ agenticRagDesc: 'Query rewriting + smart recall + re-ranking',
+ hybridSearchTitle: 'Hybrid search strategy',
+ hybridSearchDesc: 'BM25 + Vector + Knowledge Graph',
+ smartDocRetrievalTitle: 'Intelligent document retrieval',
+ smartDocRetrievalDesc: 'PDF/Word/Image multi-format parsing'
+ }
+ },
+ time: {
+ today: 'Today',
+ yesterday: 'Yesterday',
+ last7Days: 'Last 7 Days',
+ last30Days: 'Last 30 Days',
+ lastYear: 'Last Year',
+ earlier: 'Earlier'
+ },
+ upload: {
+ uploadDocument: 'Upload Document',
+ onlineEdit: 'Online Edit',
+ deleteRecord: 'Delete Record'
+ },
+ agentSettings: {
+ title: 'Agent Settings',
+ description: 'Configure the default behavior and parameters for the AI Agent. These settings apply to all chats with Agent mode enabled.',
+ status: {
+ label: 'Agent Status',
+ ready: 'Ready',
+ notReady: 'Not Ready',
+ hint: 'Once configuration is complete, the status will change to "Ready". You can then enable Agent mode in the chat.',
+ missingThinkingModel: 'Thinking model',
+ missingRerankModel: 'Rerank model',
+ missingAllowedTools: 'Allowed tools',
+ pleaseConfigure: 'Please configure {items}'
+ },
+ maxIterations: {
+ label: 'Max Iterations',
+ desc: 'Maximum reasoning steps when the Agent executes tasks'
+ },
+ thinkingModel: {
+ label: 'Thinking Model',
+ desc: 'LLM used for Agent reasoning and planning',
+ hint: 'Requires a function-call-capable model'
+ },
+ rerankModel: {
+ label: 'Rerank Model',
+ desc: 'Re-rank search results and normalize relevance scores'
+ },
+ model: {
+ placeholder: 'Search models...',
+ addChat: 'Add a new chat model',
+ addRerank: 'Add a new Rerank model'
+ },
+ temperature: {
+ label: 'Temperature',
+ desc: 'Controls randomness in outputs. 0 is most deterministic; 1 is most random'
+ },
+ allowedTools: {
+ label: 'Allowed Tools',
+ desc: 'Select tools the Agent can use (at least one)',
+ placeholder: 'Select tools...'
+ },
+ systemPrompt: {
+ label: 'System Prompt',
+ desc: 'Configure the Agent’s system prompt with placeholders that are resolved at runtime.',
+ availablePlaceholders: 'Available placeholders:',
+ hintPrefix: 'Tip: typing',
+ hintSuffix: 'will show available placeholders automatically',
+ custom: 'Custom Prompt',
+ disabledHint: 'Currently using the default prompt. Enable custom to apply the content below.',
+ placeholder: 'Enter the system prompt, or leave blank to use the default...'
+ },
+ reset: {
+ header: 'Reset to Default Prompt',
+ body: 'Are you sure you want to reset to the default prompt? Your custom prompt will be overwritten.'
+ },
+ errors: {
+ selectThinkingModel: 'Please select a thinking model before enabling Agent mode',
+ selectAtLeastOneTool: 'Please select at least one tool',
+ iterationsRange: 'Max iterations must be between 1 and 20',
+ temperatureRange: 'Temperature must be between 0 and 2',
+ validationFailed: 'Configuration validation failed'
+ },
+ toasts: {
+ iterationsSaved: 'Max iterations saved',
+ thinkingModelSaved: 'Thinking model saved',
+ rerankModelSaved: 'Rerank model saved',
+ temperatureSaved: 'Temperature saved',
+ toolsUpdated: 'Tools updated',
+ customPromptEnabled: 'Custom prompt enabled',
+ defaultPromptEnabled: 'Switched to default prompt',
+ resetToDefault: 'Reset to default prompt',
+ systemPromptSaved: 'System prompt saved',
+ autoDisabled: 'Agent configuration incomplete. Agent mode has been disabled automatically'
+ }
+ },
+ // New: MCP Settings
+ mcpSettings: {
+ title: 'MCP Services',
+ description: 'Manage external MCP (Model Context Protocol) services for tools/resources in Agent mode',
+ configuredServices: 'Configured Services',
+ manageAndTest: 'Manage and test MCP service connections',
+ addService: 'Add Service',
+ empty: 'No MCP services',
+ addFirst: 'Add the first MCP service',
+ actions: {
+ test: 'Test Connection'
+ },
+ toasts: {
+ loadFailed: 'Failed to load MCP services',
+ enabled: 'MCP service enabled',
+ disabled: 'MCP service disabled',
+ updateStateFailed: 'Failed to update MCP service status',
+ testing: 'Testing {name}...',
+ noResponse: 'Test failed: no response from server',
+ testFailed: 'Failed to test MCP service',
+ deleted: 'MCP service deleted',
+ deleteFailed: 'Failed to delete MCP service'
+ },
+ deleteConfirmBody: 'Delete MCP service “{name}”? This action cannot be undone.',
+ unnamed: 'Unnamed'
+ },
+ // New: Model Settings
+ modelSettings: {
+ title: 'Model Settings',
+ description: 'Manage different types of AI models, including local Ollama and remote APIs',
+ actions: {
+ addModel: 'Add Model',
+ setDefault: 'Set as Default'
+ },
+ source: {
+ remote: 'Remote',
+ openaiCompatible: 'OpenAI-compatible'
+ },
+ chat: {
+ title: 'Chat Models',
+ desc: 'Configure large language models for chatting',
+ empty: 'No chat models'
+ },
+ embedding: {
+ title: 'Embedding Models',
+ desc: 'Configure embedding models for text vectorization',
+ empty: 'No embedding models'
+ },
+ rerank: {
+ title: 'ReRank Models',
+ desc: 'Configure models for result re-ranking',
+ empty: 'No re-rank models'
+ },
+ vllm: {
+ title: 'VLLM Vision Models',
+ desc: 'Configure vision-language models for multimodal understanding',
+ empty: 'No VLLM models'
+ },
+ toasts: {
+ nameRequired: 'Model name cannot be empty',
+ nameTooLong: 'Model name cannot exceed 100 characters',
+ baseUrlRequired: 'Base URL is required for remote APIs',
+ baseUrlInvalid: 'Invalid Base URL, please enter a valid URL',
+ dimensionInvalid: 'Embedding dimension must be between 128 and 4096',
+ updated: 'Model updated',
+ added: 'Model added',
+ saveFailed: 'Failed to save model',
+ deleted: 'Model deleted',
+ deleteFailed: 'Failed to delete model',
+ setDefault: 'Set as default',
+ setDefaultFailed: 'Failed to set default model'
+ },
+ confirmDelete: 'Are you sure you want to delete this model?'
+ },
+ // New: Ollama Settings
+ ollamaSettings: {
+ title: 'Ollama Settings',
+ description: 'Manage local Ollama service and view/download models',
+ status: {
+ label: 'Ollama Service Status',
+ desc: 'Automatically detect local Ollama service availability. If the service is down or the URL is incorrect, status will be “Unavailable”.',
+ testing: 'Testing',
+ available: 'Available',
+ unavailable: 'Unavailable',
+ untested: 'Not Tested',
+ retest: 'Retest'
+ },
+ address: {
+ label: 'Service URL',
+ desc: 'The API address of the local Ollama service, auto-detected by the system. To modify, set it in the .env file.',
+ placeholder: 'http://localhost:11434',
+ failed: 'Connection failed. Please check whether Ollama is running or the URL is correct'
+ },
+ download: {
+ title: 'Download Models',
+ descPrefix: 'Enter a model name to download,',
+ browse: 'Browse Ollama model library',
+ placeholder: 'e.g. qwen2.5:0.5b',
+ download: 'Download',
+ downloading: 'Downloading: {name}'
+ },
+ installed: {
+ title: 'Installed Models',
+ desc: 'Models installed in Ollama',
+ empty: 'No installed models'
+ },
+ toasts: {
+ connected: 'Connected successfully',
+ connectFailed: 'Connection failed. Please check whether Ollama is running',
+ listFailed: 'Failed to get model list',
+ downloadFailed: 'Download failed. Please try again later',
+ downloadStarted: 'Started downloading model {name}',
+ downloadCompleted: 'Model {name} downloaded successfully',
+ progressFailed: 'Failed to query download progress'
+ }
+ },
+ // New: MCP Service Dialog
+ mcpServiceDialog: {
+ addTitle: 'Add MCP Service',
+ editTitle: 'Edit MCP Service',
+ name: 'Service Name',
+ namePlaceholder: 'Enter service name',
+ description: 'Description',
+ descriptionPlaceholder: 'Enter service description',
+ transportType: 'Transport Type',
+ transport: {
+ sse: 'SSE (Server-Sent Events)',
+ httpStreamable: 'HTTP Streamable',
+ stdio: 'Stdio'
+ },
+ serviceUrl: 'Service URL',
+ serviceUrlPlaceholder: 'https://example.com/mcp',
+ command: 'Command',
+ args: 'Arguments',
+ argPlaceholder: 'Argument {index}',
+ addArg: 'Add Argument',
+ envVars: 'Environment Variables',
+ envKeyPlaceholder: 'Key',
+ envValuePlaceholder: 'Value',
+ addEnvVar: 'Add Environment Variable',
+ enableService: 'Enable Service',
+ authConfig: 'Authentication',
+ apiKey: 'API Key',
+ bearerToken: 'Bearer Token',
+ optional: 'Optional',
+ advancedConfig: 'Advanced',
+ timeoutSec: 'Timeout (s)',
+ retryCount: 'Retry Count',
+ retryDelaySec: 'Retry Delay (s)',
+ rules: {
+ nameRequired: 'Please enter the service name',
+ transportRequired: 'Please select a transport type',
+ urlRequired: 'Please enter the service URL',
+ urlInvalid: 'Please enter a valid URL',
+ commandRequired: 'Please select a command (uvx or npx)',
+ argsRequired: 'Please enter at least one argument'
+ },
+ toasts: {
+ created: 'MCP service created',
+ updated: 'MCP service updated',
+ createFailed: 'Failed to create MCP service',
+ updateFailed: 'Failed to update MCP service'
+ }
}
}
\ No newline at end of file
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index a8b6e53d9..5fa686230 100644
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -15,6 +15,7 @@ export default {
knowledgeBase: {
title: 'База знаний',
list: 'Список баз знаний',
+ fileContent: 'Содержимое файла',
detail: 'Детали базы знаний',
create: 'Создать базу знаний',
edit: 'Редактировать базу знаний',
@@ -67,6 +68,10 @@ export default {
totalSize: 'Общий размер',
// Дополнительные переводы для KnowledgeBase.vue
newSession: 'Новый диалог',
+ editDocument: 'Редактировать документ',
+ draft: 'Черновик',
+ draftTip: 'Временно сохранён, не участвует в поиске',
+ untitledDocument: 'Документ без названия',
deleteDocument: 'Удалить документ',
parsingFailed: 'Парсинг не удался',
parsingInProgress: 'Парсинг...',
@@ -107,39 +112,30 @@ export default {
emptyKnowledgeDragDrop: 'База знаний пуста, перетащите файлы для загрузки',
pdfDocFormat: 'Файлы pdf, doc формата, не более 10 МБ',
textMarkdownFormat: 'Файлы text, markdown формата, не более 200 КБ',
- dragFileNotText: 'Пожалуйста, перетащите файлы, а не текст или ссылки'
+ dragFileNotText: 'Пожалуйста, перетащите файлы, а не текст или ссылки',
+ searchPlaceholder: 'Поиск по базам знаний...',
+ noMatch: 'Совпадающих баз знаний не найдено',
+ noKnowledge: 'Нет доступных баз знаний',
+ loadingFailed: 'Не удалось загрузить базы знаний'
},
- chat: {
- title: 'Диалог',
- newChat: 'Новый чат',
- inputPlaceholder: 'Введите ваше сообщение...',
- send: 'Отправить',
- thinking: 'Думаю...',
- regenerate: 'Сгенерировать заново',
+ agent: {
+ taskLabel: 'Задача:',
copy: 'Копировать',
- delete: 'Удалить',
- reference: 'Ссылка',
- noMessages: 'Нет сообщений',
- // Дополнительные переводы для компонентов чата
- waitingForAnswer: 'Ожидание ответа...',
- cannotAnswer: 'Извините, я не могу ответить на этот вопрос.',
- summarizingAnswer: 'Подведение итогов ответа...',
- loading: 'Загрузка...',
- enterDescription: 'Введите описание',
- referencedContent: 'Использовано {count} связанных материалов',
- deepThinking: 'Глубокое мышление завершено',
- knowledgeBaseQandA: 'Вопросы и ответы на основе базы знаний',
- askKnowledgeBase: 'Задайте вопрос базе знаний',
- sourcesCount: '{count} источников',
- pleaseEnterContent: 'Пожалуйста, введите содержимое!',
- pleaseUploadKnowledgeBase: 'Пожалуйста, сначала загрузите базу знаний!',
- replyingPleaseWait: 'Идёт ответ, пожалуйста, попробуйте позже!',
- createSessionFailed: 'Не удалось создать сеанс',
- createSessionError: 'Ошибка создания сеанса',
- unableToGetKnowledgeBaseId: 'Невозможно получить ID базы знаний'
+ addToKnowledgeBase: 'Добавить в базу знаний',
+ updatePlan: 'Обновить план',
+ webSearchFound: 'Найдено <strong>{count}</strong> результатов веб‑поиска',
+ argumentsLabel: 'Параметры',
+ toolFallback: 'Инструмент'
},
settings: {
title: 'Настройки',
+ modelConfig: 'Настройки модели',
+ agentConfig: 'Настройки агента',
+ webSearchConfig: 'Сетевой поиск',
+ mcpService: 'Сервис MCP',
+ systemSettings: 'Настройки системы',
+ tenantInfo: 'Информация о арендаторе',
+ apiInfo: 'Информация API',
system: 'Настройки системы',
systemConfig: 'Системная конфигурация',
knowledgeBaseSettings: 'Настройки базы знаний',
@@ -178,6 +174,35 @@ export default {
saveFailedSettings: 'Не удалось сохранить настройки',
enterNameRequired: 'Введите название'
},
+ webSearchSettings: {
+ title: 'Настройки веб-поиска',
+ description: 'Настройте веб-поиск, чтобы ответы могли включать актуальную информацию из интернета.',
+ providerLabel: 'Провайдер поиска',
+ providerDescription: 'Выберите поисковый сервис, используемый для веб-поиска',
+ providerPlaceholder: 'Выберите поисковую систему...',
+ apiKeyLabel: 'API-ключ',
+ apiKeyDescription: 'Введите API-ключ выбранного провайдера поиска',
+ apiKeyPlaceholder: 'Введите API-ключ',
+ maxResultsLabel: 'Максимум результатов',
+ maxResultsDescription: 'Максимальное количество результатов за один поиск (1-50)',
+ includeDateLabel: 'Включать дату публикации',
+ includeDateDescription: 'Добавлять информацию о дате публикации в результаты поиска',
+ compressionLabel: 'Метод сжатия',
+ compressionDescription: 'Выберите, как обрабатывать содержимое результатов поиска',
+ compressionNone: 'Без сжатия',
+ compressionSummary: 'LLM-конспект',
+ blacklistLabel: 'Чёрный список URL',
+ blacklistDescription: 'Исключите домены или URL из результатов. По одному в строке. Поддерживаются подстановки (*) и регулярные выражения (/pattern/).',
+ blacklistPlaceholder: 'Например:\n*://*.example.com/*\n/example\\.(net|org)/',
+ errors: {
+ unknown: 'Неизвестная ошибка'
+ },
+ toasts: {
+ loadProvidersFailed: 'Не удалось загрузить список поисковых провайдеров: {message}',
+ saveSuccess: 'Настройки веб-поиска сохранены',
+ saveFailed: 'Не удалось сохранить настройки: {message}'
+ }
+ },
initialization: {
title: 'Инициализация',
welcome: 'Добро пожаловать в WeKnora',
@@ -431,12 +456,21 @@ export default {
registerError: 'Ошибка регистрации, пожалуйста, повторите попытку позже',
forgotPasswordNotAvailable: 'Функция восстановления пароля временно недоступна, пожалуйста, свяжитесь с администратором'
},
+ authStore: {
+ errors: {
+ parseUserFailed: 'Не удалось разобрать данные пользователя',
+ parseTenantFailed: 'Не удалось разобрать данные арендатора',
+ parseKnowledgeBasesFailed: 'Не удалось разобрать список баз знаний',
+ parseCurrentKnowledgeBaseFailed: 'Не удалось разобрать текущую базу знаний'
+ }
+ },
common: {
confirm: 'Подтвердить',
cancel: 'Отмена',
save: 'Сохранить',
delete: 'Удалить',
edit: 'Редактировать',
+ default: 'По умолчанию',
create: 'Создать',
search: 'Поиск',
filter: 'Фильтр',
@@ -451,6 +485,7 @@ export default {
success: 'Успешно',
warning: 'Предупреждение',
info: 'Информация',
+ selectAll: 'Выбрать все',
yes: 'Да',
no: 'Нет',
ok: 'OK',
@@ -460,7 +495,14 @@ export default {
finish: 'Завершить',
all: 'Все',
reset: 'Сбросить',
- clear: 'Очистить'
+ clear: 'Очистить',
+ website: 'Официальный сайт',
+ github: 'GitHub',
+ wechat: '微信公众号',
+ on: 'Вкл',
+ off: 'Выкл',
+ resetToDefault: 'Сбросить по умолчанию',
+ confirmDelete: 'Подтвердить удаление'
},
file: {
upload: 'Загрузить файл',
@@ -477,6 +519,8 @@ export default {
},
tenant: {
title: 'Информация об арендаторе',
+ sectionDescription: 'Просмотр детальной конфигурации арендатора',
+ apiDocument: 'Документация API',
name: 'Имя арендатора',
id: 'ID арендатора',
createdAt: 'Дата создания',
@@ -515,11 +559,89 @@ export default {
useApiKey: 'Используйте ваш API Key для начала разработки, просмотрите полную документацию API и примеры кода.',
viewApiDoc: 'Просмотреть документацию API',
loadingAccountInfo: 'Загрузка информации об учётной записи...',
+ loadingInfo: 'Загрузка данных...',
loadFailed: 'Загрузка не удалась',
retry: 'Повторить',
apiKeyCopied: 'API Key скопирован в буфер обмена',
unknown: 'Неизвестно',
- formatError: 'Ошибка формата'
+ formatError: 'Ошибка формата',
+ details: {
+ idLabel: 'ID арендатора',
+ idDescription: 'Уникальный идентификатор вашего арендатора',
+ nameLabel: 'Название арендатора',
+ nameDescription: 'Название арендатора, к которому вы принадлежите',
+ descriptionLabel: 'Описание арендатора',
+ descriptionDescription: 'Подробное описание арендатора',
+ businessLabel: 'Бизнес арендатора',
+ businessDescription: 'Бизнес-направление, к которому относится арендатор',
+ statusLabel: 'Статус арендатора',
+ statusDescription: 'Текущий рабочий статус арендатора',
+ createdAtLabel: 'Время создания арендатора',
+ createdAtDescription: 'Дата и время создания арендатора'
+ },
+ storage: {
+ quotaLabel: 'Квота хранения',
+ quotaDescription: 'Общий объём хранилища, выделенный арендатору',
+ usedLabel: 'Использовано хранения',
+ usedDescription: 'Объём уже использованного пространства',
+ usageLabel: 'Использование хранения',
+ usageDescription: 'Процент использованного пространства'
+ },
+ messages: {
+ fetchFailed: 'Не удалось получить информацию об арендаторе',
+ networkError: 'Ошибка сети, попробуйте позже'
+ },
+ api: {
+ title: 'Информация об API',
+ description: 'Просматривайте и управляйте своим API-ключом',
+ keyLabel: 'API Key',
+ keyDescription: 'Ключ для API-запросов. Храните его в безопасности.',
+ copyTitle: 'Скопировать API Key',
+ docLabel: 'Документация API',
+ docDescription: 'Ознакомьтесь с полной документацией и примерами API,',
+ openDoc: 'Открыть документацию',
+ userSectionTitle: 'Информация о пользователе',
+ userIdLabel: 'ID пользователя',
+ userIdDescription: 'Ваш уникальный идентификатор пользователя',
+ usernameLabel: 'Имя пользователя',
+ usernameDescription: 'Имя, используемое для входа',
+ emailLabel: 'Электронная почта',
+ emailDescription: 'Ваш зарегистрированный адрес электронной почты',
+ createdAtLabel: 'Время регистрации',
+ createdAtDescription: 'Время создания учётной записи',
+ noKey: 'API Key отсутствует',
+ copySuccess: 'API Key скопирован в буфер обмена',
+ copyFailed: 'Не удалось скопировать, пожалуйста, сделайте это вручную'
+ }
+ },
+ system: {
+ title: 'Системная информация',
+ sectionDescription: 'Просмотр сведений о версии системы и конфигурации учётной записи пользователя',
+ loadingInfo: 'Загрузка данных...',
+ retry: 'Повторить',
+ versionLabel: 'Версия системы',
+ versionDescription: 'Текущий номер версии системы',
+ buildTimeLabel: 'Время сборки',
+ buildTimeDescription: 'Время, когда система была собрана',
+ goVersionLabel: 'Версия Go',
+ goVersionDescription: 'Версия языка Go, используемая backend',
+ unknown: 'Неизвестно',
+ messages: {
+ fetchFailed: 'Не удалось получить информацию о системе',
+ networkError: 'Ошибка сети, попробуйте позже'
+ }
+ },
+ mcp: {
+ testResult: {
+ title: 'Результат теста: {name}',
+ connectionSuccess: 'Соединение установлено',
+ connectionFailed: 'Соединение не удалось',
+ toolsTitle: 'Доступные инструменты',
+ resourcesTitle: 'Доступные ресурсы',
+ descriptionLabel: 'Описание',
+ schemaLabel: 'Структура параметров',
+ emptyDescription: 'Сервис не предоставил инструменты или ресурсы'
+ }
},
error: {
network: 'Ошибка сети',
@@ -548,6 +670,730 @@ export default {
topP: 'Top P',
selectModel: 'Выберите модель',
customModel: 'Пользовательская модель',
- builtinModel: 'Встроенная модель'
+ builtinModel: 'Встроенная модель',
+ defaultTag: 'По умолчанию',
+ addModelInSettings: 'Перейти в общие настройки для добавления моделей',
+ loadFailed: 'Не удалось загрузить список моделей',
+ selectModelPlaceholder: 'Выберите модель',
+ searchPlaceholder: 'Поиск моделей...',
+ editor: {
+ addTitle: 'Добавить модель',
+ editTitle: 'Редактировать модель',
+ sourceLabel: 'Источник модели',
+ sourceLocal: 'Ollama (локальный)',
+ sourceRemote: 'Remote API (удалённый)',
+ description: {
+ chat: 'Настройте языковую модель для диалогов',
+ embedding: 'Настройте модель встраивания для текстовой векторизации',
+ rerank: 'Настройте модель для повторного ранжирования результатов',
+ vllm: 'Настройте визуально-языковую модель для мультимодального понимания',
+ default: 'Настройте информацию о модели'
+ },
+ modelNamePlaceholder: {
+ local: 'например: llama2:latest',
+ remote: 'например: gpt-4, claude-3-opus',
+ localVllm: 'например: llava:latest',
+ remoteVllm: 'например: gpt-4-vision-preview'
+ },
+ baseUrlLabel: 'Base URL',
+ baseUrlPlaceholder: 'например: https://api.openai.com/v1',
+ baseUrlPlaceholderVllm: 'например: http://localhost:11434/v1',
+ apiKeyOptional: 'API Key (опционально)',
+ apiKeyPlaceholder: 'Введите API Key',
+ connectionTest: 'Проверка соединения',
+ testing: 'Проверка...',
+ testConnection: 'Проверить соединение',
+ searchPlaceholder: 'Поиск моделей...',
+ downloadLabel: 'Скачать: {keyword}',
+ refreshList: 'Обновить список',
+ dimensionLabel: 'Размерность вектора',
+ dimensionPlaceholder: 'например: 1536',
+ checkDimension: 'Определить размерность',
+ dimensionDetected: 'Определение выполнено, размерность: {value}',
+ dimensionFailed: 'Не удалось определить, введите размерность вручную',
+ remoteDimensionDetected: 'Обнаружена размерность: {value}',
+ dimensionHint: 'Модель выбрана. Нажмите «Определить размерность», чтобы автоматически получить значение.',
+ setAsDefault: 'Сделать модель по умолчанию',
+ loadModelListFailed: 'Не удалось загрузить список моделей',
+ listRefreshed: 'Список обновлён',
+ fillModelAndUrl: 'Сначала заполните идентификатор модели и Base URL',
+ remoteBaseUrlRequired: 'Для Remote API необходимо указать Base URL',
+ unsupportedModelType: 'Неподдерживаемый тип модели',
+ connectionSuccess: 'Соединение установлено',
+ connectionFailed: 'Соединение не установлено',
+ connectionConfigError: 'Соединение не установлено, проверьте конфигурацию',
+ downloadStarted: 'Начата загрузка {name}',
+ downloadCompleted: '{name} успешно загружена',
+ downloadFailed: 'Не удалось загрузить {name}',
+ downloadStartFailed: 'Не удалось запустить загрузку',
+ validation: {
+ modelNameRequired: 'Введите название модели',
+ modelNameEmpty: 'Название модели не может быть пустым',
+ modelNameMax: 'Название модели не может превышать 100 символов',
+ baseUrlRequired: 'Введите Base URL',
+ baseUrlEmpty: 'Base URL не может быть пустым',
+ baseUrlInvalid: 'Недопустимый Base URL, введите корректный адрес'
+ }
+ }
+ },
+ createChat: {
+ title: 'Вопросы и ответы на основе базы знаний — AI помощник',
+ newSessionTitle: 'Новая сессия',
+ messages: {
+ selectKnowledgeBase: 'Сначала выберите базу знаний',
+ createFailed: 'Не удалось создать сессию',
+ createError: 'Не удалось создать сессию, попробуйте позже'
+ }
+ },
+ knowledgeList: {
+ create: 'Создать базу знаний',
+ uninitializedBanner: 'Некоторые базы знаний не инициализированы. Сначала настройте модели в разделе настроек, чтобы добавлять документы.',
+ empty: {
+ title: 'Базы знаний отсутствуют',
+ description: 'Нажмите «Создать базу знаний» в правом верхнем углу, чтобы добавить первую базу.'
+ },
+ delete: {
+ confirmTitle: 'Подтверждение удаления',
+ confirmMessage: 'Удалить базу знаний «{name}»? Отменить действие будет невозможно.',
+ confirmButton: 'Удалить'
+ },
+ messages: {
+ deleted: 'База знаний удалена',
+ deleteFailed: 'Не удалось удалить базу знаний'
+ }
+ },
+ knowledgeEditor: {
+ titleCreate: 'Создать базу знаний',
+ titleEdit: 'Настройки базы знаний',
+ sidebar: {
+ basic: 'Основная информация',
+ models: 'Конфигурация моделей',
+ chunking: 'Настройки разбиения',
+ advanced: 'Дополнительные настройки'
+ },
+ basic: {
+ title: 'Основная информация',
+ description: 'Укажите название и описание базы знаний',
+ nameLabel: 'Название базы знаний',
+ namePlaceholder: 'Введите название базы знаний',
+ descriptionLabel: 'Описание базы знаний',
+ descriptionPlaceholder: 'Введите описание базы знаний (необязательно)'
+ },
+ buttons: {
+ create: 'Создать базу знаний',
+ save: 'Сохранить настройки'
+ },
+ messages: {
+ loadModelsFailed: 'Не удалось загрузить список моделей',
+ loadDataFailed: 'Не удалось загрузить данные базы знаний',
+ notFound: 'База знаний не найдена',
+ nameRequired: 'Пожалуйста, введите название базы знаний',
+ embeddingRequired: 'Пожалуйста, выберите модель встраивания',
+ summaryRequired: 'Пожалуйста, выберите модель суммаризации',
+ multimodalInvalid: 'Проверка мультимодальной конфигурации не удалась',
+ createSuccess: 'База знаний успешно создана',
+ createFailed: 'Не удалось создать базу знаний',
+ missingId: 'Отсутствует ID базы знаний',
+ buildDataFailed: 'Не удалось сформировать данные для отправки',
+ updateSuccess: 'Настройки сохранены'
+ },
+ models: {
+ title: 'Конфигурация моделей',
+ description: 'Выберите подходящие AI-модели для базы знаний',
+ llmLabel: 'LLM модель',
+ llmDesc: 'Большая языковая модель для диалогов и вопросов-ответов',
+ llmPlaceholder: 'Выберите LLM модель',
+ embeddingLabel: 'Модель встраивания',
+ embeddingDesc: 'Модель встраивания для векторизации текста',
+ embeddingPlaceholder: 'Выберите модель встраивания',
+ embeddingLocked: 'В базе знаний уже есть файлы. Модель встраивания нельзя изменить',
+ rerankLabel: 'Модель ReRank',
+ rerankDesc: 'Модель для переранжирования результатов поиска (необязательно)',
+ rerankPlaceholder: 'Выберите модель ReRank (необязательно)'
+ },
+ chunking: {
+ title: 'Настройки разбиения',
+ description: 'Настройте параметры разбиения документов для улучшения качества поиска',
+ sizeLabel: 'Размер блока',
+ sizeDescription: 'Определяет количество символов в каждом блоке (100-4000)',
+ characters: 'символов',
+ overlapLabel: 'Перекрытие блоков',
+ overlapDescription: 'Количество перекрывающихся символов между соседними блоками (0-500)',
+ separatorsLabel: 'Разделители',
+ separatorsDescription: 'Разделители, используемые при разбиении документов',
+ separatorsPlaceholder: 'Выберите разделители',
+ separators: {
+ doubleNewline: 'Двойной перевод строки (\\n\\n)',
+ singleNewline: 'Одинарный перевод строки (\\n)',
+ periodCn: 'Китайская точка (。)',
+ exclamationCn: 'Восклицательный знак (!)',
+ questionCn: 'Вопросительный знак (?)',
+ semicolonCn: 'Китайская точка с запятой (;)',
+ semicolonEn: 'Точка с запятой (;)',
+ space: 'Пробел ( )'
+ }
+ },
+ advanced: {
+ title: 'Расширенные настройки',
+ description: 'Настройте мультимодальные возможности и извлечение знаний',
+ multimodal: {
+ label: 'Мультимодальная функция',
+ description: 'Включите понимание мультимедийного контента, такого как изображения и видео',
+ vllmLabel: 'VLLM модель для зрения',
+ vllmDescription: 'Визуально-языковая модель, необходимая для мультимодального понимания',
+ vllmPlaceholder: 'Выберите VLLM модель (обязательно)',
+ storageTitle: 'Конфигурация хранилища',
+ storageTypeLabel: 'Тип хранилища',
+ storageTypeDescription: 'Выберите способ хранения мультимодальных файлов (MinIO или Tencent Cloud COS)',
+ storageTypeOptions: {
+ minio: 'MinIO',
+ cos: 'Tencent Cloud COS'
+ },
+ minio: {
+ bucketLabel: 'Имя Bucket',
+ bucketDescription: 'Название бакета MinIO (обязательно)',
+ bucketPlaceholder: 'Введите имя Bucket (обязательно)',
+ useSslLabel: 'Использовать SSL',
+ useSslDescription: 'Определяет, использовать ли SSL-соединение',
+ pathPrefixLabel: 'Префикс пути',
+ pathPrefixDescription: 'Необязательный префикс для путей хранения файлов',
+ pathPrefixPlaceholder: 'Введите префикс пути'
+ },
+ cos: {
+ secretIdLabel: 'SecretId',
+ secretIdDescription: 'ID секретного ключа Tencent Cloud API (обязательно)',
+ secretIdPlaceholder: 'Введите SecretId (обязательно)',
+ secretKeyLabel: 'SecretKey',
+ secretKeyDescription: 'Секретный ключ Tencent Cloud API (обязательно)',
+ secretKeyPlaceholder: 'Введите SecretKey (обязательно)',
+ regionLabel: 'Регион',
+ regionDescription: 'Регион, в котором находится бакет COS (обязательно)',
+ regionPlaceholder: 'Например: ap-guangzhou (обязательно)',
+ bucketLabel: 'Имя Bucket',
+ bucketDescription: 'Название бакета COS (обязательно)',
+ bucketPlaceholder: 'Введите имя Bucket (обязательно)',
+ appIdLabel: 'AppId',
+ appIdDescription: 'ID приложения Tencent Cloud (обязательно)',
+ appIdPlaceholder: 'Введите AppId (обязательно)',
+ pathPrefixLabel: 'Префикс пути',
+ pathPrefixDescription: 'Необязательный префикс для путей хранения файлов',
+ pathPrefixPlaceholder: 'Введите префикс пути'
+ }
+ },
+ graph: {
+ label: 'Извлечение знаний',
+ description: 'Автоматически извлекайте сущности и связи для построения графа знаний',
+ configTitle: 'Настройки графа',
+ promptLabel: 'Текст подсказки',
+ promptDescription: 'Текст подсказки, который помогает модели извлекать сущности и связи',
+ promptPlaceholder: 'Введите текст подсказки',
+ tagsLabel: 'Теги',
+ tagsDescription: 'Предопределённые теги сущностей (несколько тегов разделяйте запятыми)',
+ tagsPlaceholder: 'Введите тег и нажмите Enter'
+ }
+ }
+ },
+ chat: {
+ title: 'Диалог',
+ newChat: 'Новый чат',
+ inputPlaceholder: 'Введите ваше сообщение...',
+ send: 'Отправить',
+ thinking: 'Думаю...',
+ regenerate: 'Сгенерировать заново',
+ copy: 'Копировать',
+ delete: 'Удалить',
+ reference: 'Ссылка',
+ noMessages: 'Нет сообщений',
+ // Дополнительные переводы для компонентов чата
+ waitingForAnswer: 'Ожидание ответа...',
+ cannotAnswer: 'Извините, я не могу ответить на этот вопрос.',
+ summarizingAnswer: 'Подведение итогов ответа...',
+ loading: 'Загрузка...',
+ enterDescription: 'Введите описание',
+ referencedContent: 'Использовано {count} связанных материалов',
+ deepThinking: 'Глубокое мышление завершено',
+ knowledgeBaseQandA: 'Вопросы и ответы на основе базы знаний',
+ askKnowledgeBase: 'Задайте вопрос базе знаний',
+ sourcesCount: '{count} источников',
+ pleaseEnterContent: 'Пожалуйста, введите содержимое!',
+ pleaseUploadKnowledgeBase: 'Пожалуйста, сначала загрузите базу знаний!',
+ replyingPleaseWait: 'Идёт ответ, пожалуйста, попробуйте позже!',
+ createSessionFailed: 'Не удалось создать сеанс',
+ createSessionError: 'Ошибка создания сеанса',
+ unableToGetKnowledgeBaseId: 'Невозможно получить ID базы знаний',
+ summaryInProgress: 'Идёт подготовка ответа…',
+ referencesTitle: 'Использовано {count} связанного материала',
+ referenceIconAlt: 'Иконка ссылок на материалы',
+ chunkIdLabel: 'ID фрагмента:',
+ documentIdLabel: 'ID документа:',
+ noPlanSteps: 'Подробные шаги не предоставлены',
+ chunkIndexLabel: 'Фрагмент №{index}',
+ chunkPositionLabel: '(позиция: {position})',
+ noRelatedChunks: 'Связанные фрагменты не найдены',
+ noSearchResults: 'Результаты поиска не найдены',
+ relevanceHigh: 'Высокая релевантность',
+ relevanceMedium: 'Средняя релевантность',
+ relevanceLow: 'Низкая релевантность',
+ relevanceWeak: 'Слабая релевантность',
+ webSearchNoResults: 'Результаты веб-поиска не найдены',
+ otherSource: 'Другие источники',
+ webGroupIntro: 'Следующие {count} записей получены из',
+ graphConfigTitle: 'Настройки графа',
+ entityTypesLabel: 'Типы сущностей:',
+ relationTypesLabel: 'Типы связей:',
+ graphResultsHeader: 'Найдено {count} связанных результатов',
+ graphNoResults: 'Данные графа не найдены',
+ unknownLink: 'Неизвестная ссылка',
+ contentLengthLabel: 'Длина {value}',
+ notProvided: 'Не указано',
+ promptLabel: 'Промпт',
+ errorMessageLabel: 'Сообщение об ошибке',
+ summaryLabel: 'Сводка',
+ rawTextLabel: 'Исходный текст',
+ collapseRaw: 'Свернуть оригинал',
+ expandRaw: 'Развернуть оригинал',
+ noWebContent: 'Содержимое страницы не получено',
+ lengthChars: '{value} символов',
+ lengthThousands: '{value} тыс. символов',
+ lengthTenThousands: '{value} ×10⁴ символов',
+ sqlQueryExecuted: 'Выполненный SQL-запрос:',
+ sqlResultsLabel: 'Результаты:',
+ rowsLabel: 'строк',
+ columnsLabel: 'столбцов',
+ noDatabaseRecords: 'Совпадающих записей не найдено',
+ nullValuePlaceholder: '<NULL>',
+ documentTitleLabel: 'Название документа:',
+ chunkCountLabel: 'Количество фрагментов:',
+ chunkCountValue: 'Не менее {count}',
+ statusDescription: 'Информация о статусе',
+ statusIndexed: 'Документ проиндексирован и доступен для поиска',
+ statusSearchable: 'Можно искать содержимое документа с помощью инструментов',
+ statusChunkDetailAvailable: 'Используйте get_chunk_detail для просмотра фрагментов',
+ positionLabel: 'Позиция:',
+ chunkPositionValue: 'Фрагмент №{index}',
+ contentLengthLabelSimple: 'Длина содержимого:',
+ fullContentLabel: 'Полный текст',
+ copyContent: 'Скопировать содержимое',
+ knowledgeBaseCount: '{count} баз знаний',
+ noKnowledgeBases: 'Нет доступных баз знаний',
+ rawOutputLabel: 'Исходный вывод',
+ selectKnowledgeBaseWarning: 'Пожалуйста, выберите хотя бы одну базу знаний',
+ processError: 'Ошибка обработки'
+ },
+ language: {
+ zhCN: '简体中文',
+ enUS: 'English',
+ ruRU: 'Русский',
+ selectLanguage: 'Выбрать язык',
+ language: 'Язык',
+ languageDescription: 'Выберите язык отображения интерфейса',
+ languageSaved: 'Настройки языка сохранены'
+ },
+ general: {
+ title: 'Общие настройки',
+ allSettings: 'Все настройки',
+ description: 'Настройка языка, внешнего вида и других базовых параметров',
+ settings: 'Настройки',
+ close: 'Закрыть настройки'
+ },
+ platform: {
+ subtitle: 'Корпоративная платформа интеллектуального поиска документов',
+ description: 'Упрощение понимания сложных документов и точного поиска',
+ rag: 'RAG расширенная генерация',
+ hybridSearch: 'Гибридный поиск',
+ localDeploy: 'Локальное развертывание',
+ multimodalParsing: 'Мультимодальный анализ документов',
+ hybridSearchEngine: 'Гибридная поисковая система',
+ ragQandA: 'RAG интеллектуальный вопрос-ответ',
+ independentTenant: 'Независимое пространство арендатора',
+ fullApiAccess: 'Полный доступ к API',
+ knowledgeBaseManagement: 'Управление базой знаний',
+ carousel: {
+ agenticRagTitle: 'Agentic RAG',
+ agenticRagDesc: 'Переформулировка запроса + умный отбор + повторная ранжировка',
+ hybridSearchTitle: 'Гибридная стратегия поиска',
+ hybridSearchDesc: 'BM25 + Вектор + Граф знаний',
+ smartDocRetrievalTitle: 'Интеллектуальный поиск документов',
+ smartDocRetrievalDesc: 'Многоформатный разбор PDF/Word/изображений'
+ }
+ },
+ time: {
+ today: 'Сегодня',
+ yesterday: 'Вчера',
+ last7Days: 'Последние 7 дней',
+ last30Days: 'Последние 30 дней',
+ lastYear: 'Последний год',
+ earlier: 'Ранее'
+ },
+ upload: {
+ uploadDocument: 'Загрузить документ',
+ onlineEdit: 'Онлайн редактирование',
+ deleteRecord: 'Удалить запись'
+ },
+ // Новые разделы
+ agentSettings: {
+ title: 'Настройки Agent',
+ description: 'Настройте поведение и параметры AI Agent. Эти параметры применяются ко всем чатам с включённым режимом Agent.',
+ status: {
+ label: 'Статус Agent',
+ ready: 'Готов',
+ notReady: 'Не готов',
+ hint: 'После завершения конфигурации статус автоматически изменится на «Готов». Затем можно включить режим Agent в диалоге.',
+ missingThinkingModel: 'модель мышления',
+ missingRerankModel: 'модель ранжирования',
+ missingAllowedTools: 'разрешённые инструменты',
+ pleaseConfigure: 'Пожалуйста, настройте: {items}'
+ },
+ maxIterations: {
+ label: 'Макс. число итераций',
+ desc: 'Максимальное число шагов рассуждений при выполнении задач'
+ },
+ thinkingModel: {
+ label: 'Модель мышления',
+ desc: 'LLM для рассуждений и планирования',
+ hint: 'Требуется модель с поддержкой function call'
+ },
+ rerankModel: {
+ label: 'Модель Rerank',
+ desc: 'Повторная ранжировка результатов поиска и нормализация релевантности'
+ },
+ model: {
+ placeholder: 'Поиск моделей...',
+ addChat: 'Добавить новую модель диалога',
+ addRerank: 'Добавить новую модель Rerank'
+ },
+ temperature: {
+ label: 'Температура',
+ desc: 'Контролирует случайность ответа. 0 — детерминированно, 1 — максимально случайно'
+ },
+ allowedTools: {
+ label: 'Разрешённые инструменты',
+ desc: 'Выберите инструменты, которые может использовать Agent (минимум один)',
+ placeholder: 'Выберите инструменты...'
+ },
+ systemPrompt: {
+ label: 'Системный промпт',
+ desc: 'Настройте системный промпт Agent. Подстановки будут заменены во время выполнения.',
+ availablePlaceholders: 'Доступные подстановки:',
+ hintPrefix: 'Подсказка: при вводе',
+ hintSuffix: 'откроется список доступных подстановок',
+ custom: 'Пользовательский промпт',
+ disabledHint: 'Сейчас используется промпт по умолчанию. Включите пользовательский, чтобы применить содержимое ниже.',
+ placeholder: 'Введите системный промпт или оставьте пустым для значения по умолчанию...'
+ },
+ reset: {
+ header: 'Сбросить к промпту по умолчанию',
+ body: 'Сбросить к значению по умолчанию? Текущий пользовательский промпт будет перезаписан.'
+ },
+ errors: {
+ selectThinkingModel: 'Выберите модель мышления перед включением режима Agent',
+ selectAtLeastOneTool: 'Выберите хотя бы один инструмент',
+ iterationsRange: 'Макс. число итераций должно быть от 1 до 20',
+ temperatureRange: 'Температура должна быть от 0 до 2',
+ validationFailed: 'Ошибка проверки конфигурации'
+ },
+ toasts: {
+ iterationsSaved: 'Макс. число итераций сохранено',
+ thinkingModelSaved: 'Модель мышления сохранена',
+ rerankModelSaved: 'Модель Rerank сохранена',
+ temperatureSaved: 'Температура сохранена',
+ toolsUpdated: 'Инструменты обновлены',
+ customPromptEnabled: 'Пользовательский промпт включён',
+ defaultPromptEnabled: 'Включён промпт по умолчанию',
+ resetToDefault: 'Восстановлено значение по умолчанию',
+ systemPromptSaved: 'Системный промпт сохранён',
+ autoDisabled: 'Конфигурация Agent неполная. Режим Agent автоматически выключен'
+ }
+ },
+ mcpSettings: {
+ title: 'Сервисы MCP',
+ description: 'Управление внешними сервисами MCP (Model Context Protocol) для использования инструментов и ресурсов в режиме Agent',
+ configuredServices: 'Настроенные сервисы',
+ manageAndTest: 'Управляйте и тестируйте подключения MCP',
+ addService: 'Добавить сервис',
+ empty: 'Сервисы MCP отсутствуют',
+ addFirst: 'Добавить первый сервис MCP',
+ actions: {
+ test: 'Тест соединения'
+ },
+ toasts: {
+ loadFailed: 'Не удалось загрузить список MCP сервисов',
+ enabled: 'Сервис MCP включён',
+ disabled: 'Сервис MCP выключен',
+ updateStateFailed: 'Не удалось обновить статус сервиса MCP',
+ testing: 'Тестируем {name}...',
+ noResponse: 'Тест не удался: нет ответа от сервера',
+ testFailed: 'Не удалось протестировать сервис MCP',
+ deleted: 'Сервис MCP удалён',
+ deleteFailed: 'Не удалось удалить сервис MCP'
+ },
+ deleteConfirmBody: 'Удалить сервис MCP «{name}»? Действие необратимо.',
+ unnamed: 'Без названия'
+ },
+ modelSettings: {
+ title: 'Настройки моделей',
+ description: 'Управление типами AI‑моделей: локальные (Ollama) и удалённые API',
+ actions: {
+ addModel: 'Добавить модель',
+ setDefault: 'Сделать по умолчанию'
+ },
+ chat: {
+ title: 'Модели диалога',
+ desc: 'Модели для диалога',
+ empty: 'Нет моделей диалога'
+ },
+ source: {
+ remote: 'Удалённая',
+ openaiCompatible: 'Совместимо с OpenAI'
+ },
+ embedding: {
+ title: 'Модели встраивания',
+ desc: 'Модели для векторизации текста',
+ empty: 'Нет моделей встраивания'
+ },
+ rerank: {
+ title: 'Модели ReRank',
+ desc: 'Модели для повторной ранжировки результатов',
+ empty: 'Нет моделей ReRank'
+ },
+ vllm: {
+ title: 'VLLM модели зрения',
+ desc: 'Визуально-языковые модели для мультимодального понимания',
+ empty: 'Нет VLLM моделей'
+ },
+ toasts: {
+ nameRequired: 'Название модели не может быть пустым',
+ nameTooLong: 'Название модели не может превышать 100 символов',
+ baseUrlRequired: 'Для удалённых API требуется Base URL',
+ baseUrlInvalid: 'Некорректный Base URL, укажите правильный адрес',
+ dimensionInvalid: 'Размерность встраивания должна быть 128–4096',
+ updated: 'Модель обновлена',
+ added: 'Модель добавлена',
+ saveFailed: 'Не удалось сохранить модель',
+ deleted: 'Модель удалена',
+ deleteFailed: 'Не удалось удалить модель',
+ setDefault: 'Установлено по умолчанию',
+ setDefaultFailed: 'Не удалось установить по умолчанию'
+ },
+ confirmDelete: 'Удалить эту модель?'
+ },
+ ollamaSettings: {
+ title: 'Настройки Ollama',
+ description: 'Управление локальным сервисом Ollama и моделями',
+ status: {
+ label: 'Статус Ollama',
+ desc: 'Автоматическая проверка доступности локального сервиса Ollama. При ошибке адреса или остановке сервиса статус будет «Недоступно».',
+ testing: 'Проверка',
+ available: 'Доступно',
+ unavailable: 'Недоступно',
+ untested: 'Не проверено',
+ retest: 'Проверить снова'
+ },
+ address: {
+ label: 'Адрес сервиса',
+ desc: 'API‑адрес локального сервиса Ollama, определяется автоматически. Чтобы изменить, задайте значение в .env',
+ placeholder: 'http://localhost:11434',
+ failed: 'Ошибка подключения. Проверьте, запущен ли Ollama и корректен ли адрес'
+ },
+ download: {
+ title: 'Загрузка моделей',
+ descPrefix: 'Введите имя модели для загрузки,',
+ browse: 'Открыть каталог моделей Ollama',
+ placeholder: 'например: qwen2.5:0.5b',
+ download: 'Скачать',
+ downloading: 'Загрузка: {name}'
+ },
+ installed: {
+ title: 'Установленные модели',
+ desc: 'Список моделей, установленных в Ollama',
+ empty: 'Установленные модели отсутствуют'
+ },
+ toasts: {
+ connected: 'Соединение установлено',
+ connectFailed: 'Не удалось подключиться. Проверьте, запущен ли Ollama',
+ listFailed: 'Не удалось получить список моделей',
+ downloadFailed: 'Не удалось загрузить. Попробуйте позже',
+ downloadStarted: 'Начата загрузка модели {name}',
+ downloadCompleted: 'Модель {name} загружена',
+ progressFailed: 'Не удалось получить прогресс загрузки'
+ }
+ },
+ mcpServiceDialog: {
+ addTitle: 'Добавить сервис MCP',
+ editTitle: 'Редактировать сервис MCP',
+ name: 'Название сервиса',
+ namePlaceholder: 'Введите название сервиса',
+ description: 'Описание',
+ descriptionPlaceholder: 'Введите описание сервиса',
+ transportType: 'Тип транспорта',
+ transport: {
+ sse: 'SSE (Server-Sent Events)',
+ httpStreamable: 'HTTP Streamable',
+ stdio: 'Stdio'
+ },
+ serviceUrl: 'URL сервиса',
+ serviceUrlPlaceholder: 'https://example.com/mcp',
+ command: 'Команда',
+ args: 'Аргументы',
+ argPlaceholder: 'Аргумент {index}',
+ addArg: 'Добавить аргумент',
+ envVars: 'Переменные окружения',
+ envKeyPlaceholder: 'Имя переменной',
+ envValuePlaceholder: 'Значение',
+ addEnvVar: 'Добавить переменную',
+ enableService: 'Включить сервис',
+ authConfig: 'Аутентификация',
+ apiKey: 'API Key',
+ bearerToken: 'Bearer Token',
+ optional: 'Необязательно',
+ advancedConfig: 'Дополнительно',
+ timeoutSec: 'Таймаут (с)',
+ retryCount: 'Число попыток',
+ retryDelaySec: 'Задержка (с)',
+ rules: {
+ nameRequired: 'Введите название сервиса',
+ transportRequired: 'Выберите тип транспорта',
+ urlRequired: 'Введите URL сервиса',
+ urlInvalid: 'Введите корректный URL',
+ commandRequired: 'Выберите команду (uvx или npx)',
+ argsRequired: 'Введите хотя бы один аргумент'
+ },
+ toasts: {
+ created: 'Сервис MCP создан',
+ updated: 'Сервис MCP обновлён',
+ createFailed: 'Не удалось создать сервис MCP',
+ updateFailed: 'Не удалось обновить сервис MCP'
+ }
+ },
+ manualEditor: {
+ placeholders: {
+ heading: 'Заголовок {level}',
+ listItem: 'Элемент списка',
+ taskItem: 'Задача',
+ quote: 'Текст цитаты',
+ code: 'Содержимое кода',
+ linkText: 'Текст ссылки',
+ imageAlt: 'Описание',
+ bold: 'Жирный текст',
+ italic: 'Курсив',
+ strike: 'Зачеркнутый текст',
+ inlineCode: 'code'
+ },
+ table: {
+ column1: 'Колонка 1',
+ column2: 'Колонка 2',
+ cell: 'Содержимое'
+ },
+ toolbar: {
+ bold: 'Жирный',
+ italic: 'Курсив',
+ strike: 'Зачёркнутый',
+ inlineCode: 'Встроенный код',
+ heading1: 'Заголовок 1',
+ heading2: 'Заголовок 2',
+ heading3: 'Заголовок 3',
+ bulletList: 'Маркированный список',
+ orderedList: 'Нумерованный список',
+ taskList: 'Список задач',
+ blockquote: 'Цитата',
+ codeBlock: 'Блок кода',
+ link: 'Вставить ссылку',
+ image: 'Вставить изображение',
+ table: 'Вставить таблицу',
+ horizontalRule: 'Горизонтальная линия'
+ },
+ view: {
+ toggleToEdit: 'Переключить в режим редактирования',
+ toggleToPreview: 'Переключить в режим предпросмотра',
+ editLabel: 'Вернуться к редактированию',
+ previewLabel: 'Предпросмотр'
+ },
+ preview: {
+ empty: 'Пока нет содержимого'
+ },
+ title: {
+ edit: 'Редактировать Markdown-знание',
+ create: 'Создать Markdown-знание'
+ },
+ labels: {
+ currentKnowledgeBase: 'Текущая база знаний'
+ },
+ defaultTitlePrefix: 'Новый документ',
+ error: {
+ fetchDetailFailed: 'Не удалось получить сведения о знании',
+ saveFailed: 'Не удалось сохранить, попробуйте позже'
+ },
+ warning: {
+ selectKnowledgeBase: 'Пожалуйста, выберите целевую базу знаний',
+ enterTitle: 'Введите заголовок знания',
+ enterContent: 'Введите содержимое знания',
+ contentTooShort: 'Контент слишком короткий. Добавьте больше информации перед публикацией'
+ },
+ success: {
+ draftSaved: 'Черновик сохранён',
+ published: 'Знание опубликовано и начата индексация'
+ },
+ form: {
+ knowledgeBaseLabel: 'Целевая база знаний',
+ knowledgeBasePlaceholder: 'Выберите базу знаний',
+ titleLabel: 'Заголовок знания',
+ titlePlaceholder: 'Введите заголовок',
+ contentPlaceholder: 'Поддерживается Markdown. Используйте # заголовки, списки, блоки кода и т.д.'
+ },
+ status: {
+ draftTag: 'Статус: Черновик',
+ publishedTag: 'Статус: Опубликовано',
+ lastUpdated: 'Последнее обновление: {time}'
+ },
+ loading: {
+ content: 'Загрузка содержимого...',
+ preparing: 'Подготовка редактора...'
+ },
+ actions: {
+ cancel: 'Отмена',
+ saveDraft: 'Сохранить черновик',
+ publish: 'Опубликовать'
+ }
+ },
+ input: {
+ placeholder: 'Задайте вопрос на основе базы знаний',
+ agentMode: 'Agent режим',
+ normalMode: 'Обычный режим',
+ normalModeDesc: 'RAG-вопросы и ответы по базе знаний',
+ agentModeDesc: 'Шаблон рассуждений ReAct, многошаговое мышление',
+ agentNotReadyTooltip: 'Agent не готов. Пожалуйста, завершите настройку.',
+ agentNotReadyDetail: 'Agent не готов. Сначала завершите настройку агента в параметрах (модель мышления, модель rerank и разрешённые инструменты).',
+ goToSettings: 'Перейти к настройкам →',
+ webSearch: {
+ toggleOn: 'Включить веб-поиск',
+ toggleOff: 'Выключить веб-поиск',
+ notConfigured: 'Веб-поиск не настроен'
+ },
+ knowledgeBase: 'База знаний',
+ knowledgeBaseWithCount: 'База знаний ({count})',
+ notConfigured: 'Не настроено',
+ model: 'Модель',
+ remote: 'Удалённая',
+ noModel: 'Нет доступных моделей',
+ stopGeneration: 'Остановить генерацию',
+ send: 'Отправить',
+ thinkingLabel: 'Thinking:',
+ messages: {
+ enterContent: 'Сначала введите содержимое!',
+ selectKnowledge: 'Пожалуйста, выберите базу знаний!',
+ replying: 'Ответ формируется, попробуйте позже!',
+ agentSwitchedOn: 'Переключено в Agent режим',
+ agentSwitchedOff: 'Переключено в обычный режим',
+ agentEnabled: 'Agent режим включён',
+ agentDisabled: 'Agent режим отключён',
+ agentNotReadyDetail: 'Agent не готов. Сначала завершите настройку агента в параметрах (модель мышления, модель rerank и разрешённые инструменты).',
+ webSearchNotConfigured: 'Веб-поиск не настроен. Сначала выберите провайдера и настройте ключи в разделе настроек.',
+ webSearchEnabled: 'Веб-поиск включён',
+ webSearchDisabled: 'Веб-поиск выключен',
+ sessionMissing: 'ID сессии не существует',
+ messageMissing: 'Не удалось получить ID сообщения. Обновите страницу и попробуйте снова.',
+ stopSuccess: 'Генерация остановлена',
+ stopFailed: 'Не удалось остановить. Попробуйте ещё раз.'
+ }
}
}
\ No newline at end of file
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index b3fc5c4ef..6ad07eed2 100644
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -15,6 +15,7 @@ export default {
knowledgeBase: {
title: '知识库',
list: '知识库列表',
+ fileContent: '文件内容',
detail: '知识库详情',
create: '创建知识库',
edit: '编辑知识库',
@@ -46,7 +47,7 @@ export default {
updateFailed: '知识库更新失败',
deleteSuccess: '知识库删除成功',
deleteConfirm: '确定要删除此知识库吗?',
- fileName: '文件名',
+ fileName: '文件名称',
fileSize: '文件大小',
uploadTime: '上传时间',
status: '状态',
@@ -66,6 +67,10 @@ export default {
totalFiles: '文件总数',
totalSize: '总大小',
newSession: '新会话',
+ editDocument: '编辑文档',
+ draft: '草稿',
+ draftTip: '暂存内容,未参与检索',
+ untitledDocument: '未命名文档',
deleteDocument: '删除文档',
parsingFailed: '解析失败',
parsingInProgress: '解析中...',
@@ -105,7 +110,11 @@ export default {
emptyKnowledgeDragDrop: '知识为空,拖放上传',
pdfDocFormat: 'pdf、doc 格式文件,不超过10M',
textMarkdownFormat: 'text、markdown格式文件,不超过200K',
- dragFileNotText: '请拖拽文件而不是文本或链接'
+ dragFileNotText: '请拖拽文件而不是文本或链接',
+ searchPlaceholder: '搜索知识库...',
+ noMatch: '未找到匹配的知识库',
+ noKnowledge: '暂无可用知识库',
+ loadingFailed: '加载知识库失败'
},
chat: {
title: '对话',
@@ -135,8 +144,24 @@ export default {
createSessionError: '创建会话出错',
unableToGetKnowledgeBaseId: '无法获取知识库ID'
},
+ agent: {
+ taskLabel: '任务:',
+ copy: '复制',
+ addToKnowledgeBase: '添加到知识库',
+ updatePlan: '更新计划',
+ webSearchFound: '找到 <strong>{count}</strong> 个网络搜索结果',
+ argumentsLabel: '参数',
+ toolFallback: '工具'
+ },
settings: {
title: '设置',
+ modelConfig: '模型配置',
+ agentConfig: 'Agent配置',
+ webSearchConfig: '网络搜索',
+ mcpService: 'MCP服务',
+ systemSettings: '系统设置',
+ tenantInfo: '租户信息',
+ apiInfo: 'API信息',
system: '系统设置',
systemConfig: '系统配置',
knowledgeBaseSettings: '知识库设置',
@@ -175,6 +200,35 @@ export default {
saveFailedSettings: '设置保存失败',
enterNameRequired: '请输入名称'
},
+ webSearchSettings: {
+ title: '网络搜索配置',
+ description: '配置网络搜索功能,在回答问题时可以从互联网获取实时信息补充知识库内容',
+ providerLabel: '搜索引擎提供商',
+ providerDescription: '选择用于网络搜索的搜索引擎服务',
+ providerPlaceholder: '选择搜索引擎...',
+ apiKeyLabel: 'API 密钥',
+ apiKeyDescription: '输入所选搜索引擎的 API 密钥',
+ apiKeyPlaceholder: '请输入 API 密钥',
+ maxResultsLabel: '最大结果数',
+ maxResultsDescription: '每次搜索返回的最大结果数量(1-50)',
+ includeDateLabel: '包含发布日期',
+ includeDateDescription: '在搜索结果中包含内容的发布日期信息',
+ compressionLabel: '压缩方法',
+ compressionDescription: '对搜索结果内容的压缩处理方法',
+ compressionNone: '无压缩',
+ compressionSummary: 'LLM 摘要',
+ blacklistLabel: 'URL 黑名单',
+ blacklistDescription: '排除特定域名或 URL 的搜索结果,每行一个。支持通配符(*)和正则表达式(以/开头和结尾)',
+ blacklistPlaceholder: '例如:\n*://*.example.com/*\n/example\\.(net|org)/',
+ errors: {
+ unknown: '未知错误'
+ },
+ toasts: {
+ loadProvidersFailed: '加载搜索引擎列表失败: {message}',
+ saveSuccess: '网络搜索配置已保存',
+ saveFailed: '保存配置失败: {message}'
+ }
+ },
initialization: {
title: '初始化',
welcome: '欢迎使用WeKnora',
@@ -415,12 +469,21 @@ export default {
registerError: '注册错误,请稍后重试',
forgotPasswordNotAvailable: '密码找回功能暂不可用,请联系管理员'
},
+ authStore: {
+ errors: {
+ parseUserFailed: '解析用户信息失败',
+ parseTenantFailed: '解析租户信息失败',
+ parseKnowledgeBasesFailed: '解析知识库列表失败',
+ parseCurrentKnowledgeBaseFailed: '解析当前知识库失败'
+ }
+ },
common: {
confirm: '确认',
cancel: '取消',
save: '保存',
delete: '删除',
edit: '编辑',
+ default: '默认',
create: '创建',
search: '搜索',
filter: '筛选',
@@ -435,6 +498,7 @@ export default {
success: '成功',
warning: '警告',
info: '信息',
+ selectAll: '全选',
yes: '是',
no: '否',
ok: '确定',
@@ -444,7 +508,12 @@ export default {
finish: '完成',
all: '全部',
reset: '重置',
- clear: '清空'
+ clear: '清空',
+ website: '官方网站',
+ on: '开启',
+ off: '关闭',
+ resetToDefault: '恢复默认',
+ confirmDelete: '确认删除'
},
file: {
upload: '上传文件',
@@ -461,6 +530,8 @@ export default {
},
tenant: {
title: '租户信息',
+ sectionDescription: '查看租户的详细配置信息',
+ apiDocument: 'API文档',
name: '租户名称',
id: '租户ID',
createdAt: '创建时间',
@@ -498,13 +569,93 @@ export default {
useApiKey: '使用您的API密钥开始开发,查看完整的API文档和代码示例。',
viewApiDoc: '查看API文档',
loadingAccountInfo: '加载账户信息中...',
+ loadingInfo: '正在加载信息...',
loadFailed: '加载失败',
retry: '重试',
apiKeyCopied: 'API密钥已复制到剪贴板',
unknown: '未知',
formatError: '格式错误'
+ ,
+ details: {
+ idLabel: '租户 ID',
+ idDescription: '您所属租户的唯一标识',
+ nameLabel: '租户名称',
+ nameDescription: '您所属的租户名称',
+ descriptionLabel: '租户描述',
+ descriptionDescription: '租户的详细描述信息',
+ businessLabel: '租户业务',
+ businessDescription: '租户所属的业务类型',
+ statusLabel: '租户状态',
+ statusDescription: '租户当前的运行状态',
+ createdAtLabel: '租户创建时间',
+ createdAtDescription: '租户创建的时间'
+ },
+ storage: {
+ quotaLabel: '存储配额',
+ quotaDescription: '租户的总存储空间配额',
+ usedLabel: '已使用存储',
+ usedDescription: '已经使用的存储空间',
+ usageLabel: '存储使用率',
+ usageDescription: '存储空间的使用百分比'
+ },
+ messages: {
+ fetchFailed: '获取租户信息失败',
+ networkError: '网络错误,请稍后重试'
+ },
+ api: {
+ title: 'API 信息',
+ description: '查看和管理您的 API 密钥',
+ keyLabel: 'API Key',
+ keyDescription: '用于 API 调用的密钥,请妥善保管',
+ copyTitle: '复制 API Key',
+ docLabel: 'API 文档',
+ docDescription: '查看完整的 API 调用文档和示例,',
+ openDoc: '打开文档',
+ userSectionTitle: '用户信息',
+ userIdLabel: '用户 ID',
+ userIdDescription: '您的唯一用户标识',
+ usernameLabel: '用户名',
+ usernameDescription: '您的登录用户名',
+ emailLabel: '邮箱',
+ emailDescription: '您的注册邮箱地址',
+ createdAtLabel: '注册时间',
+ createdAtDescription: '账户创建的时间',
+ noKey: '暂无 API Key',
+ copySuccess: 'API Key 已复制到剪贴板',
+ copyFailed: '复制失败,请手动复制'
+ }
+ },
+ system: {
+ title: '系统信息',
+ sectionDescription: '查看系统版本信息和用户账户配置',
+ loadingInfo: '正在加载信息...',
+ retry: '重试',
+ versionLabel: '系统版本',
+ versionDescription: '当前系统的版本号',
+ buildTimeLabel: '构建时间',
+ buildTimeDescription: '系统构建的时间',
+ goVersionLabel: 'Go 版本',
+ goVersionDescription: '后端使用的 Go 语言版本',
+ unknown: '未知',
+ messages: {
+ fetchFailed: '获取系统信息失败',
+ networkError: '网络错误,请稍后重试'
+ }
+ },
+ mcp: {
+ testResult: {
+ title: '测试结果: {name}',
+ connectionSuccess: '连接成功',
+ connectionFailed: '连接失败',
+ toolsTitle: '可用工具',
+ resourcesTitle: '可用资源',
+ descriptionLabel: '描述',
+ schemaLabel: '参数结构',
+ emptyDescription: '该服务未提供工具或资源'
+ }
},
error: {
+ invalidImageLink: '无效的图片链接',
network: '网络错误',
server: '服务器错误',
notFound: '未找到',
@@ -531,6 +682,715 @@ export default {
topP: 'Top P',
selectModel: '选择模型',
customModel: '自定义模型',
- builtinModel: '内置模型'
+ builtinModel: '内置模型',
+ defaultTag: '默认',
+ addModelInSettings: '前往全局设置添加模型',
+ loadFailed: '加载模型列表失败',
+ selectModelPlaceholder: '请选择模型',
+ searchPlaceholder: '搜索模型...',
+ editor: {
+ addTitle: '添加模型',
+ editTitle: '编辑模型',
+ sourceLabel: '模型来源',
+ sourceLocal: 'Ollama(本地)',
+ sourceRemote: 'Remote API(远程)',
+ description: {
+ chat: '配置用于对话的大语言模型',
+ embedding: '配置用于文本向量化的嵌入模型',
+ rerank: '配置用于结果重排序的模型',
+ vllm: '配置用于视觉理解和多模态的视觉语言模型',
+ default: '配置模型信息'
+ },
+ modelNamePlaceholder: {
+ local: '例如:llama2:latest',
+ remote: '例如:gpt-4, claude-3-opus',
+ localVllm: '例如:llava:latest',
+ remoteVllm: '例如:gpt-4-vision-preview'
+ },
+ baseUrlLabel: 'Base URL',
+ baseUrlPlaceholder: '例如:https://api.openai.com/v1',
+ baseUrlPlaceholderVllm: '例如:http://localhost:11434/v1',
+ apiKeyOptional: 'API Key(可选)',
+ apiKeyPlaceholder: '输入 API Key',
+ connectionTest: '连接测试',
+ testing: '测试中...',
+ testConnection: '测试连接',
+ searchPlaceholder: '搜索模型...',
+ downloadLabel: '下载: {keyword}',
+ refreshList: '刷新列表',
+ dimensionLabel: '向量维度',
+ dimensionPlaceholder: '例如:1536',
+ checkDimension: '检测维度',
+ dimensionDetected: '检测成功,向量维度:{value}',
+ dimensionFailed: '检测失败,请手动输入维度',
+ remoteDimensionDetected: '检测到向量维度:{value}',
+ dimensionHint: '模型已选择,点击“检测维度”按钮自动获取向量维度',
+ setAsDefault: '设为默认模型',
+ loadModelListFailed: '加载模型列表失败',
+ listRefreshed: '列表已刷新',
+ fillModelAndUrl: '请先填写模型标识和 Base URL',
+ remoteBaseUrlRequired: 'Remote API 类型必须填写 Base URL',
+ unsupportedModelType: '不支持的模型类型',
+ connectionSuccess: '连接成功',
+ connectionFailed: '连接失败',
+ connectionConfigError: '连接失败,请检查配置',
+ downloadStarted: '开始下载 {name}',
+ downloadCompleted: '{name} 下载完成',
+ downloadFailed: '{name} 下载失败',
+ downloadStartFailed: '启动下载失败',
+ validation: {
+ modelNameRequired: '请输入模型名称',
+ modelNameEmpty: '模型名称不能为空',
+ modelNameMax: '模型名称不能超过100个字符',
+ baseUrlRequired: '请输入 Base URL',
+ baseUrlEmpty: 'Base URL 不能为空',
+ baseUrlInvalid: 'Base URL 格式不正确,请输入有效的 URL'
+ }
+ }
+ },
+ language: {
+ zhCN: '简体中文',
+ enUS: 'English',
+ ruRU: 'Русский',
+ selectLanguage: '选择语言',
+ language: '语言',
+ languageDescription: '选择界面显示语言',
+ languageSaved: '语言设置已保存'
+ },
+ general: {
+ title: '常规设置',
+ allSettings: '全部设置',
+ description: '配置语言、外观等基础选项',
+ settings: '设置',
+ close: '关闭设置'
+ },
+ platform: {
+ subtitle: '企业级智能文档检索框架',
+ description: '让复杂文档理解与精准检索变得简单',
+ rag: 'RAG 增强生成',
+ hybridSearch: '混合检索',
+ localDeploy: '本地部署',
+ multimodalParsing: '多模态文档解析',
+ hybridSearchEngine: '混合检索引擎',
+ ragQandA: 'RAG 智能问答',
+ independentTenant: '独立租户空间',
+ fullApiAccess: '完整 API 访问',
+ knowledgeBaseManagement: '知识库管理',
+ carousel: {
+ agenticRagTitle: 'Agentic RAG',
+ agenticRagDesc: '问题改写 + 智能召回 + 重排序',
+ hybridSearchTitle: '混合检索策略',
+ hybridSearchDesc: 'BM25 + 向量 + 知识图谱',
+ smartDocRetrievalTitle: '智能文档检索',
+ smartDocRetrievalDesc: 'PDF/Word/图片多格式解析'
+ }
+ },
+ time: {
+ today: '今天',
+ yesterday: '昨天',
+ last7Days: '近7天',
+ last30Days: '近30天',
+ lastYear: '近1年',
+ earlier: '更早'
+ },
+ upload: {
+ uploadDocument: '上传文档',
+ onlineEdit: '在线编辑',
+ deleteRecord: '删除记录'
+ },
+ manualEditor: {
+ placeholders: {
+ heading: '标题{level}',
+ listItem: '列表项',
+ taskItem: '任务项',
+ quote: '引用内容',
+ code: '代码内容',
+ linkText: '链接文本',
+ imageAlt: '描述',
+ bold: '加粗文本',
+ italic: '斜体文本',
+ strike: '删除线',
+ inlineCode: 'code'
+ },
+ table: {
+ column1: '列1',
+ column2: '列2',
+ cell: '内容'
+ },
+ toolbar: {
+ bold: '加粗',
+ italic: '斜体',
+ strike: '删除线',
+ inlineCode: '行内代码',
+ heading1: '一级标题',
+ heading2: '二级标题',
+ heading3: '三级标题',
+ bulletList: '无序列表',
+ orderedList: '有序列表',
+ taskList: '任务列表',
+ blockquote: '引用',
+ codeBlock: '代码块',
+ link: '插入链接',
+ image: '插入图片',
+ table: '插入表格',
+ horizontalRule: '分割线'
+ },
+ view: {
+ toggleToEdit: '切换到编辑视图',
+ toggleToPreview: '切换到预览视图',
+ editLabel: '返回编辑',
+ previewLabel: '预览内容'
+ },
+ preview: {
+ empty: '暂无内容'
+ },
+ title: {
+ edit: '编辑 Markdown 知识',
+ create: '在线编辑 Markdown 知识'
+ },
+ labels: {
+ currentKnowledgeBase: '当前知识库'
+ },
+ defaultTitlePrefix: '新建文档',
+ error: {
+ fetchDetailFailed: '获取知识详情失败',
+ saveFailed: '保存失败,请稍后重试'
+ },
+ warning: {
+ selectKnowledgeBase: '请选择目标知识库',
+ enterTitle: '请输入知识标题',
+ enterContent: '请输入知识内容',
+ contentTooShort: '内容过短,建议补充更多信息后再发布'
+ },
+ success: {
+ draftSaved: '草稿已保存',
+ published: '知识已发布并开始索引'
+ },
+ form: {
+ knowledgeBaseLabel: '目标知识库',
+ knowledgeBasePlaceholder: '请选择知识库',
+ titleLabel: '知识标题',
+ titlePlaceholder: '请输入标题',
+ contentPlaceholder: '支持 Markdown 语法,可使用 # 标题、列表、代码块等'
+ },
+ status: {
+ draftTag: '当前状态:草稿',
+ publishedTag: '当前状态:已发布',
+ lastUpdated: '最近更新:{time}'
+ },
+ loading: {
+ content: '正在加载内容',
+ preparing: '正在准备编辑器'
+ },
+ actions: {
+ cancel: '取消',
+ saveDraft: '暂存草稿',
+ publish: '发布入库'
+ }
+ },
+ createChat: {
+ title: '基于知识库内容问答 - AI 问答',
+ newSessionTitle: '新会话',
+ messages: {
+ selectKnowledgeBase: '请先选择知识库',
+ createFailed: '创建会话失败',
+ createError: '创建会话失败,请稍后重试'
+ }
+ },
+ knowledgeList: {
+ create: '新建知识库',
+ uninitializedBanner: '部分知识库尚未初始化,需要先在设置中配置模型信息才能添加知识文档',
+ empty: {
+ title: '暂无知识库',
+ description: '点击右上角“新建知识库”按钮创建第一个知识库'
+ },
+ delete: {
+ confirmTitle: '删除确认',
+ confirmMessage: '确认要删除知识库“{name}”?删除后不可恢复',
+ confirmButton: '确认删除'
+ },
+ messages: {
+ deleted: '已删除',
+ deleteFailed: '删除失败'
+ }
+ },
+ knowledgeEditor: {
+ titleCreate: '新建知识库',
+ titleEdit: '知识库设置',
+ sidebar: {
+ basic: '基本信息',
+ models: '模型配置',
+ chunking: '分块设置',
+ advanced: '高级设置'
+ },
+ basic: {
+ title: '基本信息',
+ description: '设置知识库的名称和描述信息',
+ nameLabel: '知识库名称',
+ namePlaceholder: '请输入知识库名称',
+ descriptionLabel: '知识库描述',
+ descriptionPlaceholder: '请输入知识库描述(可选)'
+ },
+ buttons: {
+ create: '创建知识库',
+ save: '保存配置'
+ },
+ messages: {
+ loadModelsFailed: '加载模型列表失败',
+ loadDataFailed: '加载知识库数据失败',
+ notFound: '知识库不存在',
+ nameRequired: '请输入知识库名称',
+ embeddingRequired: '请选择 Embedding 模型',
+ summaryRequired: '请选择 Summary 模型',
+ multimodalInvalid: '多模态配置验证失败',
+ createSuccess: '知识库创建成功',
+ createFailed: '创建知识库失败',
+ missingId: '缺少知识库 ID',
+ buildDataFailed: '数据构建失败',
+ updateSuccess: '配置保存成功'
+ },
+ models: {
+ title: '模型配置',
+ description: '为知识库选择合适的 AI 模型',
+ llmLabel: 'LLM 大语言模型',
+ llmDesc: '用于对话和问答的大语言模型',
+ llmPlaceholder: '请选择 LLM 模型',
+ embeddingLabel: 'Embedding 嵌入模型',
+ embeddingDesc: '用于文本向量化的嵌入模型',
+ embeddingPlaceholder: '请选择 Embedding 模型',
+ embeddingLocked: '知识库中已有文件,无法修改 Embedding 模型',
+ rerankLabel: 'ReRank 重排序模型',
+ rerankDesc: '用于搜索结果重排序的模型(可选)',
+ rerankPlaceholder: '请选择 ReRank 模型(可选)'
+ },
+ chunking: {
+ title: '分块设置',
+ description: '配置文档分块参数,优化检索效果',
+ sizeLabel: '分块大小',
+ sizeDescription: '控制每个文档分块的字符数(100-4000)',
+ characters: '字符',
+ overlapLabel: '分块重叠',
+ overlapDescription: '相邻文档块之间的重叠字符数(0-500)',
+ separatorsLabel: '分隔符',
+ separatorsDescription: '文档分块时使用的分隔符',
+ separatorsPlaceholder: '选择分隔符',
+ separators: {
+ doubleNewline: '双换行 (\\n\\n)',
+ singleNewline: '单换行 (\\n)',
+ periodCn: '中文句号 (。)',
+ exclamationCn: '感叹号 (!)',
+ questionCn: '问号 (?)',
+ semicolonCn: '中文分号 (;)',
+ semicolonEn: '英文分号 (;)',
+ space: '空格 ( )'
+ }
+ },
+ advanced: {
+ title: '高级设置',
+ description: '配置多模态、知识图谱等高级功能',
+ multimodal: {
+ label: '多模态功能',
+ description: '启用图片、视频等多模态内容的理解能力',
+ vllmLabel: 'VLLM 视觉模型',
+ vllmDescription: '用于多模态理解的视觉语言模型(必选)',
+ vllmPlaceholder: '请选择 VLLM 模型(必选)',
+ storageTitle: '存储配置',
+ storageTypeLabel: '存储类型',
+ storageTypeDescription: '选择多模态文件的存储方式(MinIO 或腾讯云 COS 二选一)',
+ storageTypeOptions: {
+ minio: 'MinIO',
+ cos: '腾讯云 COS'
+ },
+ minio: {
+ bucketLabel: 'Bucket 名称',
+ bucketDescription: 'MinIO 存储桶名称(必填)',
+ bucketPlaceholder: '请输入 Bucket 名称(必填)',
+ useSslLabel: '使用 SSL',
+ useSslDescription: '是否使用 SSL 连接',
+ pathPrefixLabel: '路径前缀',
+ pathPrefixDescription: '文件存储路径前缀(可选)',
+ pathPrefixPlaceholder: '请输入路径前缀'
+ },
+ cos: {
+ secretIdLabel: 'SecretId',
+ secretIdDescription: '腾讯云 API 密钥 ID(必填)',
+ secretIdPlaceholder: '请输入 SecretId(必填)',
+ secretKeyLabel: 'SecretKey',
+ secretKeyDescription: '腾讯云 API 密钥 Key(必填)',
+ secretKeyPlaceholder: '请输入 SecretKey(必填)',
+ regionLabel: '地域',
+ regionDescription: 'COS 存储桶所在地域(必填)',
+ regionPlaceholder: '如:ap-guangzhou(必填)',
+ bucketLabel: 'Bucket 名称',
+ bucketDescription: 'COS 存储桶名称(必填)',
+ bucketPlaceholder: '请输入 Bucket 名称(必填)',
+ appIdLabel: 'AppId',
+ appIdDescription: '腾讯云应用 ID(必填)',
+ appIdPlaceholder: '请输入 AppId(必填)',
+ pathPrefixLabel: '路径前缀',
+ pathPrefixDescription: '文件存储路径前缀(可选)',
+ pathPrefixPlaceholder: '请输入路径前缀'
+ }
+ },
+ graph: {
+ label: '知识图谱提取',
+ description: '从文档中自动提取实体和关系,构建知识图谱',
+ configTitle: '图谱配置',
+ promptLabel: '提示文本',
+ promptDescription: '用于引导模型提取实体和关系的提示文本',
+ promptPlaceholder: '请输入提示文本',
+ tagsLabel: '标签',
+ tagsDescription: '预定义的实体标签(多个标签用逗号分隔)',
+ tagsPlaceholder: '输入标签后按回车'
+ }
+ }
+ },
+ input: {
+ placeholder: '基于知识库提问',
+ agentMode: 'Agent 模式',
+ normalMode: '普通模式',
+ normalModeDesc: '基于知识库的 RAG 问答',
+ agentModeDesc: 'ReAct 推理框架,多步思考',
+ agentNotReadyTooltip: 'Agent 未就绪,请先在设置中完成配置',
+ agentNotReadyDetail: 'Agent 未就绪,请先在设置中完成 Agent 配置(思考模型、Rerank 模型和允许的工具)',
+ goToSettings: '前往设置 →',
+ webSearch: {
+ toggleOn: '开启网络搜索',
+ toggleOff: '关闭网络搜索',
+ notConfigured: '未配置网络搜索引擎'
+ },
+ chat: {
+ summaryInProgress: '正在总结答案……',
+ thinking: '思考中···',
+ thinkingAlt: '正在思考',
+ deepThoughtCompleted: '已深度思考',
+ deepThoughtAlt: '深度思考完成',
+ referencesTitle: '参考了{count}个相关内容',
+ referenceIconAlt: '参考内容图标',
+ chunkIdLabel: '片段ID:',
+ documentIdLabel: '文档ID:',
+ noPlanSteps: '未提供具体步骤',
+ chunkIndexLabel: '片段 #{index}',
+ chunkPositionLabel: '(位置: {position})',
+ noRelatedChunks: '没有找到相关片段',
+ noSearchResults: '没有找到搜索结果',
+ relevanceHigh: '高相关',
+ relevanceMedium: '中相关',
+ relevanceLow: '低相关',
+ relevanceWeak: '弱相关',
+ webSearchNoResults: '未找到搜索结果',
+ otherSource: '其他来源',
+ webGroupIntro: '以下 {count} 条内容来自',
+ graphConfigTitle: '图谱配置',
+ entityTypesLabel: '实体类型:',
+ relationTypesLabel: '关系类型:',
+ graphResultsHeader: '找到 {count} 条相关结果',
+ graphNoResults: '未找到相关的图谱信息',
+ unknownLink: '未知链接',
+ contentLengthLabel: '长度 {value}',
+ notProvided: '未提供',
+ promptLabel: '提示词',
+ errorMessageLabel: '错误信息',
+ summaryLabel: '总结',
+ rawTextLabel: '原始文本',
+ collapseRaw: '收起原文',
+ expandRaw: '展开原文',
+ noWebContent: '未获取到网页内容',
+ lengthChars: '{value} 字',
+ lengthThousands: '{value} 千字',
+ lengthTenThousands: '{value} 万字',
+ sqlQueryExecuted: '执行的 SQL 查询:',
+ sqlResultsLabel: '返回结果:',
+ rowsLabel: '行',
+ columnsLabel: '列',
+ noDatabaseRecords: '未找到匹配的记录',
+ nullValuePlaceholder: '<NULL>',
+ documentTitleLabel: '文档标题:',
+ chunkCountLabel: '片段数量:',
+ chunkCountValue: '至少 {count} 个',
+ statusDescription: '状态说明',
+ statusIndexed: '文档已索引并可搜索',
+ statusSearchable: '可使用搜索工具查找文档内容',
+ statusChunkDetailAvailable: '可使用 get_chunk_detail 查看片段详情',
+ positionLabel: '位置:',
+ chunkPositionValue: '第 {index} 个片段',
+ contentLengthLabelSimple: '内容长度:',
+ fullContentLabel: '完整内容',
+ copyContent: '复制内容',
+ knowledgeBaseCount: '共 {count} 个知识库',
+ noKnowledgeBases: '没有可用的知识库',
+ enterDescription: '请输入描述文案',
+ rawOutputLabel: '原始输出',
+ waitingForAnswer: '正在等待答案……',
+ cannotAnswer: '抱歉,我无法回答这个问题。',
+ selectKnowledgeBaseWarning: '请至少选择一个知识库',
+ processError: '处理出错'
+ },
+ knowledgeBase: '知识库',
+ knowledgeBaseWithCount: '知识库({count})',
+ notConfigured: '未配置',
+ model: '模型',
+ remote: '远程',
+ noModel: '暂无可用模型',
+ stopGeneration: '停止生成',
+ send: '发送',
+ thinkingLabel: 'Thinking:',
+ messages: {
+ enterContent: '请先输入内容!',
+ selectKnowledge: '请先选择知识库!',
+ replying: '正在回复中,请稍后再试!',
+ agentSwitchedOn: '已切换到 Agent 模式',
+ agentSwitchedOff: '已切换到普通模式',
+ agentEnabled: 'Agent 模式已启用',
+ agentDisabled: 'Agent 模式已禁用',
+ agentNotReadyDetail: 'Agent 未就绪,请先在设置中完成 Agent 配置(思考模型、Rerank 模型和允许的工具)',
+ webSearchNotConfigured: '未配置网络搜索引擎,请先在设置中完成搜索引擎选择与接口配置。',
+ webSearchEnabled: '网络搜索已开启',
+ webSearchDisabled: '网络搜索已关闭',
+ sessionMissing: '会话 ID 不存在',
+ messageMissing: '无法获取消息 ID,请刷新页面后重试',
+ stopSuccess: '已停止生成',
+ stopFailed: '停止失败,请重试'
+ },
+ },
+ // 新增:Agent 设置
+ agentSettings: {
+ title: 'Agent 配置',
+ description: '配置 AI Agent 的默认行为和参数,这些设置将应用于所有启用 Agent 模式的对话',
+ status: {
+ label: 'Agent 状态',
+ ready: '可用',
+ notReady: '未就绪',
+ hint: '配置完成后,Agent 状态将自动变为“可用”,此时可在对话界面开启 Agent 模式',
+ missingThinkingModel: '思考模型',
+ missingRerankModel: 'Rerank 模型',
+ missingAllowedTools: '允许的工具',
+ pleaseConfigure: '请配置{items}'
+ },
+ maxIterations: {
+ label: '最大迭代次数',
+ desc: 'Agent 执行任务时的最大推理步骤数'
+ },
+ thinkingModel: {
+ label: '思考模型',
+ desc: '用于 Agent 推理和规划的 LLM 模型',
+ hint: '需要支持 Function call 的大尺寸模型,如 deepseek 等'
+ },
+ rerankModel: {
+ label: 'Rerank 模型',
+ desc: '搜索结果重排序,统一不同来源的相关度分数'
+ },
+ model: {
+ placeholder: '搜索模型...',
+ addChat: '添加新的对话模型',
+ addRerank: '添加新的 Rerank 模型'
+ },
+ temperature: {
+ label: '温度参数',
+ desc: '控制模型输出的随机性,0 最确定,1 最随机'
+ },
+ allowedTools: {
+ label: '允许的工具',
+ desc: '选择 Agent 可以使用的工具,至少选择一个',
+ placeholder: '请选择工具...'
+ },
+ systemPrompt: {
+ label: '系统 Prompt',
+ desc: '配置 Agent 的系统提示词,支持占位符模板。占位符会在运行时自动替换为实际内容。',
+ availablePlaceholders: '可用占位符:',
+ hintPrefix: '提示:输入',
+ hintSuffix: '时会自动显示可用占位符',
+ custom: '自定义 Prompt',
+ disabledHint: '当前使用系统默认 Prompt,开启自定义后才会应用下方内容。',
+ placeholder: '请输入系统 Prompt,或留空使用默认 Prompt...'
+ },
+ reset: {
+ header: '恢复默认 Prompt',
+ body: '确定要恢复为默认 Prompt 吗?当前的自定义 Prompt 将被覆盖。'
+ },
+ errors: {
+ selectThinkingModel: '启用Agent模式前,请先选择思考模型',
+ selectAtLeastOneTool: '至少需要选择一个允许的工具',
+ iterationsRange: '最大迭代次数必须在1-20之间',
+ temperatureRange: '温度参数必须在0-2之间',
+ validationFailed: '配置验证失败'
+ },
+ toasts: {
+ iterationsSaved: '最大迭代次数已保存',
+ thinkingModelSaved: '思考模型已保存',
+ rerankModelSaved: 'Rerank 模型已保存',
+ temperatureSaved: '温度参数已保存',
+ toolsUpdated: '工具配置已更新',
+ customPromptEnabled: '已启用自定义 Prompt',
+ defaultPromptEnabled: '已切换为默认 Prompt',
+ resetToDefault: '已恢复为默认 Prompt',
+ systemPromptSaved: '系统 Prompt 已保存',
+ autoDisabled: 'Agent 配置不完整,已自动关闭 Agent 模式'
+ }
+ },
+ // 新增:MCP 设置
+ mcpSettings: {
+ title: 'MCP 服务管理',
+ description: '管理外部 MCP (Model Context Protocol) 服务,在 Agent 模式下调用外部工具和资源',
+ configuredServices: '已配置的服务',
+ manageAndTest: '管理和测试 MCP 服务连接',
+ addService: '添加服务',
+ empty: '暂无 MCP 服务',
+ addFirst: '添加第一个 MCP 服务',
+ actions: {
+ test: '测试连接'
+ },
+ toasts: {
+ loadFailed: '加载 MCP 服务列表失败',
+ enabled: '已启用 MCP 服务',
+ disabled: '已禁用 MCP 服务',
+ updateStateFailed: '更新 MCP 服务状态失败',
+ testing: '正在测试 {name}...',
+ noResponse: '测试失败:未收到服务器响应',
+ testFailed: '测试 MCP 服务失败',
+ deleted: 'MCP 服务已删除',
+ deleteFailed: '删除 MCP 服务失败'
+ },
+ deleteConfirmBody: '确定要删除 MCP 服务“{name}”吗?此操作无法撤销。',
+ unnamed: '未命名'
+ },
+
+ // 新增:模型设置
+ modelSettings: {
+ title: '模型配置',
+ description: '管理不同类型的 AI 模型,支持 Ollama 本地模型和远程 API',
+ actions: {
+ addModel: '添加模型',
+ setDefault: '设为默认'
+ },
+ source: {
+ remote: 'Remote',
+ openaiCompatible: 'OpenAI兼容'
+ },
+ chat: {
+ title: '对话模型',
+ desc: '配置用于对话的大语言模型',
+ empty: '暂无对话模型'
+ },
+ embedding: {
+ title: 'Embedding 模型',
+ desc: '配置用于文本向量化的嵌入模型',
+ empty: '暂无 Embedding 模型'
+ },
+ rerank: {
+ title: 'ReRank 模型',
+ desc: '配置用于结果重排序的模型',
+ empty: '暂无 ReRank 模型'
+ },
+ vllm: {
+ title: 'VLLM 视觉模型',
+ desc: '配置用于视觉理解和多模态的视觉语言模型',
+ empty: '暂无 VLLM 视觉模型'
+ },
+ toasts: {
+ nameRequired: '模型名称不能为空',
+ nameTooLong: '模型名称不能超过100个字符',
+ baseUrlRequired: 'Remote API 类型必须填写 Base URL',
+ baseUrlInvalid: 'Base URL 格式不正确,请输入有效的 URL',
+ dimensionInvalid: 'Embedding 模型必须填写有效的向量维度(128-4096)',
+ updated: '模型已更新',
+ added: '模型已添加',
+ saveFailed: '保存模型失败',
+ deleted: '模型已删除',
+ deleteFailed: '删除模型失败',
+ setDefault: '已设为默认模型',
+ setDefaultFailed: '设置默认模型失败'
+ },
+ confirmDelete: '确定删除此模型吗?'
+ },
+ // 新增:Ollama 设置
+ ollamaSettings: {
+ title: 'Ollama 配置',
+ description: '管理本地 Ollama 服务,查看和下载模型',
+ status: {
+ label: 'Ollama 服务状态',
+ desc: '自动检测本地 Ollama 服务是否可用。如果服务未运行或地址配置错误,将显示“不可用”状态',
+ testing: '检测中',
+ available: '可用',
+ unavailable: '不可用',
+ untested: '未检测',
+ retest: '重新检测'
+ },
+ address: {
+ label: '服务地址',
+ desc: '本地 Ollama 服务的 API 地址,由系统自动检测。如需修改,请在 .env 配置文件中设置',
+ placeholder: 'http://localhost:11434',
+ failed: '连接失败,请检查 Ollama 是否运行或服务地址是否正确'
+ },
+ download: {
+ title: '下载新模型',
+ descPrefix: '输入模型名称下载,',
+ browse: '浏览 Ollama 模型库',
+ placeholder: '如:qwen2.5:0.5b',
+ download: '下载',
+ downloading: '正在下载: {name}'
+ },
+ installed: {
+ title: '已下载的模型',
+ desc: '已安装在 Ollama 中的模型列表',
+ empty: '暂无已下载的模型'
+ },
+ toasts: {
+ connected: '连接成功',
+ connectFailed: '连接失败,请检查 Ollama 是否运行',
+ listFailed: '获取模型列表失败',
+ downloadFailed: '下载失败,请稍后重试',
+ downloadStarted: '已开始下载模型 {name}',
+ downloadCompleted: '模型 {name} 下载完成',
+ progressFailed: '查询下载进度失败'
+ }
+ },
+ // 新增:MCP 服务对话框
+ mcpServiceDialog: {
+ addTitle: '添加 MCP 服务',
+ editTitle: '编辑 MCP 服务',
+ name: '服务名称',
+ namePlaceholder: '请输入服务名称',
+ description: '描述',
+ descriptionPlaceholder: '请输入服务描述',
+ transportType: '传输类型',
+ transport: {
+ sse: 'SSE (Server-Sent Events)',
+ httpStreamable: 'HTTP Streamable',
+ stdio: 'Stdio'
+ },
+ serviceUrl: '服务 URL',
+ serviceUrlPlaceholder: 'https://example.com/mcp',
+ command: '命令',
+ args: '参数',
+ argPlaceholder: '参数 {index}',
+ addArg: '添加参数',
+ envVars: '环境变量',
+ envKeyPlaceholder: '变量名',
+ envValuePlaceholder: '变量值',
+ addEnvVar: '添加环境变量',
+ enableService: '启用服务',
+ authConfig: '认证配置',
+ apiKey: 'API Key',
+ bearerToken: 'Bearer Token',
+ optional: '可选',
+ advancedConfig: '高级配置',
+ timeoutSec: '超时时间(秒)',
+ retryCount: '重试次数',
+ retryDelaySec: '重试延迟(秒)',
+ rules: {
+ nameRequired: '请输入服务名称',
+ transportRequired: '请选择传输类型',
+ urlRequired: '请输入服务 URL',
+ urlInvalid: '请输入有效的 URL',
+ commandRequired: '请选择命令 (uvx 或 npx)',
+ argsRequired: '请至少输入一个参数'
+ },
+ toasts: {
+ created: 'MCP 服务已创建',
+ updated: 'MCP 服务已更新',
+ createFailed: '创建 MCP 服务失败',
+ updateFailed: '更新 MCP 服务失败'
+ }
}
}
\ No newline at end of file
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index 0628e01ff..82799ce0d 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -7,10 +7,13 @@ import TDesign from "tdesign-vue-next";
// 引入组件库的少量全局样式变量
import "tdesign-vue-next/es/style/index.css";
import "@/assets/theme/theme.css";
+import i18n from "./i18n";
+
const app = createApp(App);
app.use(TDesign);
app.use(createPinia());
app.use(router);
+app.use(i18n);
app.mount("#app");
diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts
index ab8a03e04..180ee9a02 100644
--- a/frontend/src/stores/auth.ts
+++ b/frontend/src/stores/auth.ts
@@ -1,6 +1,7 @@
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { UserInfo, TenantInfo, KnowledgeBaseInfo } from '@/api/auth'
+import i18n from '@/i18n'
export const useAuthStore = defineStore('auth', () => {
// 状态
@@ -99,7 +100,7 @@ export const useAuthStore = defineStore('auth', () => {
try {
user.value = JSON.parse(storedUser)
} catch (e) {
- console.error('解析用户信息失败:', e)
+ console.error(i18n.global.t('authStore.errors.parseUserFailed'), e)
}
}
@@ -107,7 +108,7 @@ export const useAuthStore = defineStore('auth', () => {
try {
tenant.value = JSON.parse(storedTenant)
} catch (e) {
- console.error('解析租户信息失败:', e)
+ console.error(i18n.global.t('authStore.errors.parseTenantFailed'), e)
}
}
@@ -124,7 +125,7 @@ export const useAuthStore = defineStore('auth', () => {
const parsed = JSON.parse(storedKnowledgeBases)
knowledgeBases.value = Array.isArray(parsed) ? parsed : []
} catch (e) {
- console.error('解析知识库列表失败:', e)
+ console.error(i18n.global.t('authStore.errors.parseKnowledgeBasesFailed'), e)
knowledgeBases.value = []
}
}
@@ -133,7 +134,7 @@ export const useAuthStore = defineStore('auth', () => {
try {
currentKnowledgeBase.value = JSON.parse(storedCurrentKb)
} catch (e) {
- console.error('解析当前知识库失败:', e)
+ console.error(i18n.global.t('authStore.errors.parseCurrentKnowledgeBaseFailed'), e)
}
}
}
diff --git a/frontend/src/stores/menu.ts b/frontend/src/stores/menu.ts
index 628489cc9..67087ac3f 100644
--- a/frontend/src/stores/menu.ts
+++ b/frontend/src/stores/menu.ts
@@ -1,54 +1,108 @@
-import { ref, computed, reactive } from 'vue'
-
-import { defineStore } from 'pinia';
-
-export const useMenuStore = defineStore('menuStore', {
- state: () => ({
- menuArr: reactive([
- { title: '知识库', icon: 'zhishiku', path: 'knowledge-bases' },
- {
- title: '对话',
- icon: 'prefixIcon',
- path: 'creatChat',
- childrenPath: 'chat',
- children: reactive<object[]>([]),
- },
- { title: '设置', icon: 'setting', path: 'settings' },
- { title: '退出登录', icon: 'logout', path: 'logout' }
- ]),
- isFirstSession: false,
- firstQuery: ''
+import { reactive, ref, watch } from 'vue'
+import { defineStore } from 'pinia'
+import i18n from '@/i18n'
+
+type MenuChild = Record<string, any>
+
+interface MenuItem {
+ title: string
+ titleKey?: string
+ icon: string
+ path: string
+ childrenPath?: string
+ children?: MenuChild[]
+}
+
+const createMenuChildren = () => reactive<MenuChild[]>([])
+
+export const useMenuStore = defineStore('menuStore', () => {
+ const menuArr = reactive<MenuItem[]>([
+ { title: '', titleKey: 'menu.knowledgeBase', icon: 'zhishiku', path: 'knowledge-bases' },
+ {
+ title: '',
+ titleKey: 'menu.chat',
+ icon: 'prefixIcon',
+ path: 'creatChat',
+ childrenPath: 'chat',
+ children: createMenuChildren()
+ },
+ { title: '', titleKey: 'menu.settings', icon: 'setting', path: 'settings' },
+ { title: '', titleKey: 'menu.logout', icon: 'logout', path: 'logout' }
+ ])
+
+ const isFirstSession = ref(false)
+ const firstQuery = ref('')
+
+ const applyMenuTranslations = () => {
+ menuArr.forEach(item => {
+ if (item.titleKey) {
+ item.title = i18n.global.t(item.titleKey)
+ }
+ })
+ }
+
+ applyMenuTranslations()
+
+ watch(
+ () => i18n.global.locale.value,
+ () => {
+ applyMenuTranslations()
}
- ),
- actions: {
- clearMenuArr() {
- this.menuArr[1].children = reactive<object[]>([]);
- },
- updatemenuArr(obj: any) {
- // 检查是否已存在相同 ID 的 session,避免重复添加
- const exists = this.menuArr[1].children?.some((item: any) => item.id === obj.id);
- if (!exists) {
- this.menuArr[1].children?.push(obj);
- }
- },
- updataMenuChildren(item: object) {
- this.menuArr[1].children?.unshift(item)
- },
- updatasessionTitle(session_id: string, title: string) {
- this.menuArr[1].children?.forEach((item: any) => {
- if (item.id == session_id) {
- item.title = title;
- item.isNoTitle = false;
- }
- });
- },
- changeIsFirstSession(payload: boolean) {
- this.isFirstSession = payload;
- },
- changeFirstQuery(payload: string) {
- this.firstQuery = payload;
- }
+ )
+
+ const clearMenuArr = () => {
+ const chatMenu = menuArr[1]
+ if (chatMenu && chatMenu.children) {
+ chatMenu.children = createMenuChildren()
+ }
+ }
+
+ const updatemenuArr = (obj: any) => {
+ const chatMenu = menuArr[1]
+ if (!chatMenu.children) {
+ chatMenu.children = createMenuChildren()
+ }
+ const exists = chatMenu.children.some((item: MenuChild) => item.id === obj.id)
+ if (!exists) {
+ chatMenu.children.push(obj)
}
-});
+ }
+
+ const updataMenuChildren = (item: MenuChild) => {
+ const chatMenu = menuArr[1]
+ if (!chatMenu.children) {
+ chatMenu.children = createMenuChildren()
+ }
+ chatMenu.children.unshift(item)
+ }
+
+ const updatasessionTitle = (sessionId: string, title: string) => {
+ const chatMenu = menuArr[1]
+ chatMenu.children?.forEach((item: MenuChild) => {
+ if (item.id === sessionId) {
+ item.title = title
+ item.isNoTitle = false
+ }
+ })
+ }
+
+ const changeIsFirstSession = (payload: boolean) => {
+ isFirstSession.value = payload
+ }
+ const changeFirstQuery = (payload: string) => {
+ firstQuery.value = payload
+ }
+ return {
+ menuArr,
+ isFirstSession,
+ firstQuery,
+ clearMenuArr,
+ updatemenuArr,
+ updataMenuChildren,
+ updatasessionTitle,
+ changeIsFirstSession,
+ changeFirstQuery
+ }
+})
diff --git a/frontend/src/views/auth/Login.vue b/frontend/src/views/auth/Login.vue
index 72fa3e788..2cf47593f 100644
--- a/frontend/src/views/auth/Login.vue
+++ b/frontend/src/views/auth/Login.vue
@@ -179,22 +179,22 @@
</div>
<!-- Logo - Top Left -->
- <a href="https://github.com/Tencent/WeKnora" target="_blank" class="header-logo" title="GitHub 仓库">
+ <a href="https://github.com/Tencent/WeKnora" target="_blank" class="header-logo" :title="$t('common.github')">
<img src="@/assets/img/weknora.png" alt="WeKnora" class="logo-image" />
</a>
<!-- Header Links - Top Right -->
<div class="header-links">
- <a href="https://weknora.weixin.qq.com" target="_blank" class="header-link" title="官方网站">
+ <a href="https://weknora.weixin.qq.com" target="_blank" class="header-link" :title="$t('common.website')">
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round">
<circle cx="12" cy="12" r="10"/>
<line x1="2" y1="12" x2="22" y2="12"/>
<path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
</svg>
- <span class="link-text">官网</span>
+ <span class="link-text">{{ $t('common.website') }}</span>
</a>
- <a href="https://github.com/Tencent/WeKnora" target="_blank" class="header-link" title="GitHub 仓库">
+ <a href="https://github.com/Tencent/WeKnora" target="_blank" class="header-link" :title="$t('common.info')">
<svg width="17" height="17" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z"/>
</svg>
@@ -230,13 +230,13 @@
<!-- Left Showcase Section -->
<div class="showcase-section">
<div class="showcase-content">
- <p class="showcase-subtitle">企业级智能文档检索框架</p>
- <p class="showcase-description">让复杂文档理解与精准检索变得简单</p>
+ <p class="showcase-subtitle">{{ $t('platform.subtitle') }}</p>
+ <p class="showcase-description">{{ $t('platform.description') }}</p>
<div class="feature-tags">
- <span class="tag">RAG 增强生成</span>
- <span class="tag">混合检索</span>
- <span class="tag">本地部署</span>
+ <span class="tag">{{ $t('platform.rag') }}</span>
+ <span class="tag">{{ $t('platform.hybridSearch') }}</span>
+ <span class="tag">{{ $t('platform.localDeploy') }}</span>
</div>
<!-- Swiper Carousel -->
@@ -271,8 +271,8 @@
<!-- Login Card -->
<div class="form-card" v-if="!isRegisterMode">
<div class="form-header">
- <h2 class="form-title">登录账户</h2>
- <p class="form-welcome">欢迎回来,开始您的智能知识之旅</p>
+ <h2 class="form-title">{{ $t('auth.login') }}</h2>
+ <p class="form-welcome">{{ $t('auth.subtitle') }}</p>
</div>
<div class="form-content">
@@ -283,20 +283,20 @@
@submit="handleLogin"
layout="vertical"
>
- <t-form-item label="邮箱" name="email">
+ <t-form-item :label="$t('auth.email')" name="email">
<t-input
v-model="formData.email"
- placeholder="请输入邮箱地址"
+ :placeholder="$t('auth.emailPlaceholder')"
type="email"
size="large"
:disabled="loading"
/>
</t-form-item>
- <t-form-item label="密码" name="password">
+ <t-form-item :label="$t('auth.password')" name="password">
<t-input
v-model="formData.password"
- placeholder="请输入密码(8-32位,包含字母和数字)"
+ :placeholder="$t('auth.passwordPlaceholder')"
type="password"
size="large"
:disabled="loading"
@@ -312,14 +312,14 @@
:loading="loading"
class="submit-button"
>
- {{ loading ? '登录中...' : '立即登录' }}
+ {{ loading ? $t('auth.loggingIn') : $t('auth.login') }}
</t-button>
</t-form>
<div class="form-footer">
- <span>还没有账号?</span>
+ <span>{{ $t('auth.noAccount') }}</span>
<a href="#" @click.prevent="toggleMode" class="link-button">
- 立即注册
+ {{ $t('auth.registerNow') }}
</a>
</div>
@@ -327,15 +327,15 @@
<div class="login-features">
<div class="feature-item">
<span class="feature-icon">✓</span>
- <span class="feature-text">多模态文档解析</span>
+ <span class="feature-text">{{ $t('platform.multimodalParsing') }}</span>
</div>
<div class="feature-item">
<span class="feature-icon">✓</span>
- <span class="feature-text">混合检索引擎</span>
+ <span class="feature-text">{{ $t('platform.hybridSearchEngine') }}</span>
</div>
<div class="feature-item">
<span class="feature-icon">✓</span>
- <span class="feature-text">RAG 智能问答</span>
+ <span class="feature-text">{{ $t('platform.ragQandA') }}</span>
</div>
</div>
</div>
@@ -344,8 +344,8 @@
<!-- Register Card -->
<div class="form-card" v-if="isRegisterMode">
<div class="form-header">
- <h2 class="form-title">创建账户</h2>
- <p class="form-subtitle">注册后系统将为您创建专属租户</p>
+ <h2 class="form-title">{{ $t('auth.createAccount') }}</h2>
+ <p class="form-subtitle">{{ $t('auth.registerSubtitle') }}</p>
</div>
<div class="form-content">
@@ -356,39 +356,39 @@
@submit="handleRegister"
layout="vertical"
>
- <t-form-item label="用户名" name="username">
+ <t-form-item :label="$t('auth.username')" name="username">
<t-input
v-model="registerData.username"
- placeholder="请输入用户名"
+ :placeholder="$t('auth.usernamePlaceholder')"
size="large"
:disabled="loading"
/>
</t-form-item>
- <t-form-item label="邮箱" name="email">
+ <t-form-item :label="$t('auth.email')" name="email">
<t-input
v-model="registerData.email"
- placeholder="请输入邮箱地址"
+ :placeholder="$t('auth.emailPlaceholder')"
type="email"
size="large"
:disabled="loading"
/>
</t-form-item>
- <t-form-item label="密码" name="password">
+ <t-form-item :label="$t('auth.password')" name="password">
<t-input
v-model="registerData.password"
- placeholder="请输入密码(8-32位,包含字母和数字)"
+ :placeholder="$t('auth.passwordPlaceholder')"
type="password"
size="large"
:disabled="loading"
/>
</t-form-item>
- <t-form-item label="确认密码" name="confirmPassword">
+ <t-form-item :label="$t('auth.confirmPassword')" name="confirmPassword">
<t-input
v-model="registerData.confirmPassword"
- placeholder="请再次输入密码"
+ :placeholder="$t('auth.confirmPasswordPlaceholder')"
type="password"
size="large"
:disabled="loading"
@@ -404,14 +404,14 @@
:loading="loading"
class="submit-button"
>
- {{ loading ? '注册中...' : '注册' }}
+ {{ loading ? $t('auth.registering') : $t('auth.register') }}
</t-button>
</t-form>
<div class="form-footer">
- <span>已有账号?</span>
+ <span>{{ $t('auth.haveAccount') }}</span>
<a href="#" @click.prevent="toggleMode" class="link-button">
- 返回登录
+ {{ $t('auth.backToLogin') }}
</a>
</div>
@@ -419,15 +419,15 @@
<div class="login-features">
<div class="feature-item">
<span class="feature-icon">✓</span>
- <span class="feature-text">独立租户空间</span>
+ <span class="feature-text">{{ $t('platform.independentTenant') }}</span>
</div>
<div class="feature-item">
<span class="feature-icon">✓</span>
- <span class="feature-text">完整 API 访问</span>
+ <span class="feature-text">{{ $t('platform.fullApiAccess') }}</span>
</div>
<div class="feature-item">
<span class="feature-icon">✓</span>
- <span class="feature-text">知识库管理</span>
+ <span class="feature-text">{{ $t('platform.knowledgeBaseManagement') }}</span>
</div>
</div>
</div>
@@ -438,7 +438,7 @@
</template>
<script setup lang="ts">
-import { ref, reactive, nextTick, onMounted } from 'vue'
+import { ref, reactive, nextTick, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next'
import { Swiper, SwiperSlide } from 'swiper/vue'
@@ -448,6 +448,7 @@ import 'swiper/css/effect-fade'
import 'swiper/css/pagination'
import { login, register } from '@/api/auth'
import { useAuthStore } from '@/stores/auth'
+import { useI18n } from 'vue-i18n'
// Import screenshot images
import screenshot1 from '@/assets/img/screenshot-1.svg'
@@ -456,6 +457,7 @@ import screenshot4 from '@/assets/img/screenshot-4.svg'
const router = useRouter()
const authStore = useAuthStore()
+const { t, locale } = useI18n()
// Swiper modules
const modules = [Autoplay, EffectFade, Pagination]
@@ -464,18 +466,18 @@ const modules = [Autoplay, EffectFade, Pagination]
const slides = [
{
image: screenshot4,
- title: 'Agentic RAG',
- description: '问题改写 + 智能召回 + 重排序'
+ title: t('platform.carousel.agenticRagTitle'),
+ description: t('platform.carousel.agenticRagDesc')
},
{
image: screenshot2,
- title: '混合检索策略',
- description: 'BM25 + 向量 + 知识图谱'
+ title: t('platform.carousel.hybridSearchTitle'),
+ description: t('platform.carousel.hybridSearchDesc')
},
{
image: screenshot1,
- title: '智能文档检索',
- description: 'PDF/Word/图片多格式解析'
+ title: t('platform.carousel.smartDocRetrievalTitle'),
+ description: t('platform.carousel.smartDocRetrievalDesc')
}
]
@@ -486,16 +488,18 @@ const registerFormRef = ref()
// State management
const loading = ref(false)
const isRegisterMode = ref(false)
-const currentLanguage = ref('zh') // 'zh', 'en', or 'ru'
const showLanguageMenu = ref(false)
// Language options
const languageOptions = [
- { value: 'zh', label: '简体中文', shortLabel: '中文', flag: '🇨🇳' },
- { value: 'en', label: 'English', shortLabel: 'EN', flag: '🇺🇸' },
- { value: 'ru', label: 'Русский', shortLabel: 'RU', flag: '🇷🇺' }
+ { value: 'zh-CN', label: '简体中文', shortLabel: '中文', flag: '🇨🇳' },
+ { value: 'en-US', label: 'English', shortLabel: 'EN', flag: '🇺🇸' },
+ { value: 'ru-RU', label: 'Русский', shortLabel: 'RU', flag: '🇷🇺' }
]
+// Current language computed from i18n
+const currentLanguage = computed(() => locale.value)
+
// Login form data
const formData = reactive<{[key: string]: any}>({
email: '',
@@ -511,52 +515,52 @@ const registerData = reactive<{[key: string]: any}>({
})
// Login form validation rules
-const formRules = {
+const formRules = computed(() => ({
email: [
- { required: true, message: '请输入邮箱地址', type: 'error' },
- { email: true, message: '请输入正确的邮箱格式', type: 'error' }
+ { required: true, message: t('auth.emailRequired'), type: 'error' },
+ { email: true, message: t('auth.emailInvalid'), type: 'error' }
],
password: [
- { required: true, message: '请输入密码', type: 'error' },
- { min: 8, message: '密码至少8位', type: 'error' },
- { max: 32, message: '密码不能超过32位', type: 'error' },
- { pattern: /[a-zA-Z]/, message: '密码必须包含字母', type: 'error' },
- { pattern: /\d/, message: '密码必须包含数字', type: 'error' }
+ { required: true, message: t('auth.passwordRequired'), type: 'error' },
+ { min: 8, message: t('auth.passwordMinLength'), type: 'error' },
+ { max: 32, message: t('auth.passwordMaxLength'), type: 'error' },
+ { pattern: /[a-zA-Z]/, message: t('auth.passwordMustContainLetter'), type: 'error' },
+ { pattern: /\d/, message: t('auth.passwordMustContainNumber'), type: 'error' }
]
-}
+}))
// Register form validation rules
-const registerRules = {
+const registerRules = computed(() => ({
username: [
- { required: true, message: '请输入用户名', type: 'error' },
- { min: 2, message: '用户名至少2位', type: 'error' },
- { max: 20, message: '用户名不能超过20位', type: 'error' },
+ { required: true, message: t('auth.usernameRequired'), type: 'error' },
+ { min: 2, message: t('auth.usernameMinLength'), type: 'error' },
+ { max: 20, message: t('auth.usernameMaxLength'), type: 'error' },
{
pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
- message: '用户名只能包含字母、数字、下划线和中文',
+ message: t('auth.usernameInvalid'),
type: 'error'
}
],
email: [
- { required: true, message: '请输入邮箱地址', type: 'error' },
- { email: true, message: '请输入正确的邮箱格式', type: 'error' }
+ { required: true, message: t('auth.emailRequired'), type: 'error' },
+ { email: true, message: t('auth.emailInvalid'), type: 'error' }
],
password: [
- { required: true, message: '请输入密码', type: 'error' },
- { min: 8, message: '密码至少8位', type: 'error' },
- { max: 32, message: '密码不能超过32位', type: 'error' },
- { pattern: /[a-zA-Z]/, message: '密码必须包含字母', type: 'error' },
- { pattern: /\d/, message: '密码必须包含数字', type: 'error' }
+ { required: true, message: t('auth.passwordRequired'), type: 'error' },
+ { min: 8, message: t('auth.passwordMinLength'), type: 'error' },
+ { max: 32, message: t('auth.passwordMaxLength'), type: 'error' },
+ { pattern: /[a-zA-Z]/, message: t('auth.passwordMustContainLetter'), type: 'error' },
+ { pattern: /\d/, message: t('auth.passwordMustContainNumber'), type: 'error' }
],
confirmPassword: [
- { required: true, message: '请确认密码', type: 'error' },
+ { required: true, message: t('auth.confirmPasswordRequired'), type: 'error' },
{
validator: (val: string) => val === registerData.password,
- message: '两次输入的密码不一致',
+ message: t('auth.passwordMismatch'),
type: 'error'
}
]
-}
+}))
// Toggle login/register mode
const toggleMode = () => {
@@ -574,10 +578,10 @@ const toggleLanguageMenu = () => {
// Select language
const selectLanguage = (lang: string) => {
- currentLanguage.value = lang
+ locale.value = lang
+ localStorage.setItem('locale', lang)
showLanguageMenu.value = false
- // 这里可以添加实际的语言切换逻辑
- // 比如:i18n.global.locale = currentLanguage.value
+ MessagePlugin.success(t('language.languageSaved'))
}
// Close language menu when clicking outside
@@ -638,17 +642,17 @@ const handleLogin = async () => {
})
}
- MessagePlugin.success('登录成功!')
+ MessagePlugin.success(t('auth.loginSuccess'))
// Wait for state update before redirect
await nextTick()
router.replace('/platform/knowledge-bases')
} else {
- MessagePlugin.error(response.message || '登录失败,请检查邮箱或密码')
+ MessagePlugin.error(response.message || t('auth.loginError'))
}
} catch (error: any) {
console.error('登录错误:', error)
- MessagePlugin.error(error.message || '登录失败,请稍后重试')
+ MessagePlugin.error(error.message || t('auth.loginErrorRetry'))
} finally {
loading.value = false
}
@@ -669,7 +673,7 @@ const handleRegister = async () => {
})
if (response.success) {
- MessagePlugin.success('注册成功!系统已为您创建专属租户,请登录使用')
+ MessagePlugin.success(t('auth.registerSuccess'))
// Switch to login mode and fill in email
isRegisterMode.value = false
@@ -680,11 +684,11 @@ const handleRegister = async () => {
(registerData as any)[key] = ''
})
} else {
- MessagePlugin.error(response.message || '注册失败')
+ MessagePlugin.error(response.message || t('auth.registerFailed'))
}
} catch (error: any) {
console.error('注册错误:', error)
- MessagePlugin.error(error.message || '注册失败,请稍后重试')
+ MessagePlugin.error(error.message || t('auth.registerError'))
} finally {
loading.value = false
}
diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue
index 6226b9406..f81cceae1 100644
--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue
+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue
@@ -22,7 +22,7 @@
<div v-if="event.type === 'plan_task_change'" class="plan-task-change-event">
<div class="plan-task-change-card">
<div class="plan-task-change-content">
- <strong>任务:</strong> {{ event.task }}
+ <strong>{{ $t('agent.taskLabel') }}</strong> {{ event.task }}
</div>
</div>
</div>
@@ -58,10 +58,10 @@
</div>
</div>
<div v-if="event.done" class="answer-toolbar">
- <t-button size="small" variant="outline" shape="round" @click.stop="handleCopyAnswer(event)" title="复制">
+ <t-button size="small" variant="outline" shape="round" @click.stop="handleCopyAnswer(event)" :title="$t('agent.copy')">
<t-icon name="copy" />
</t-button>
- <t-button size="small" variant="outline" shape="round" @click.stop="handleAddToKnowledge(event)" title="添加到知识库">
+ <t-button size="small" variant="outline" shape="round" @click.stop="handleAddToKnowledge(event)" :title="$t('agent.addToKnowledgeBase')">
<t-icon name="add" />
</t-button>
</div>
@@ -81,9 +81,9 @@
<img v-if="event.tool_name && !isBookIcon(event.tool_name)" class="action-title-icon" :src="getToolIcon(event.tool_name)" alt="" />
<t-icon v-if="event.tool_name && isBookIcon(event.tool_name)" class="action-title-icon" name="book" />
<!-- Custom header for todo_write tool -->
- <t-tooltip v-if="event.tool_name === 'todo_write' && event.tool_data?.steps" :content="'更新计划'" placement="top">
+ <t-tooltip v-if="event.tool_name === 'todo_write' && event.tool_data?.steps" :content="t('agent.updatePlan')" placement="top">
<span class="action-name">
- 更新计划
+ {{ $t('agent.updatePlan') }}
</span>
</t-tooltip>
<!-- Use tool summary as title if available, otherwise use description -->
@@ -114,7 +114,7 @@
<!-- Web Search Results Summary (Fixed, always visible, outside action-details) -->
<div v-if="!event.pending && event.tool_name === 'web_search' && event.tool_data" class="search-results-summary-fixed">
- <div class="results-summary-text">找到 <strong>{{ getResultsCount(event.tool_data) }}</strong> 个网络搜索结果</div>
+ <div class="results-summary-text" v-html="t('agent.webSearchFound', { count: getResultsCount(event.tool_data) })"></div>
</div>
<div v-if="isEventExpanded(event.tool_call_id) && !event.pending" class="action-details">
@@ -140,7 +140,7 @@
<!-- Fallback to original output display -->
<div v-else-if="event.output" class="tool-output-wrapper">
<div class="fallback-header">
- <span class="fallback-label">原始输出</span>
+ <span class="fallback-label">{{ $t('chat.rawOutputLabel') }}</span>
</div>
<div class="detail-output-wrapper">
<div class="detail-output">{{ event.output }}</div>
@@ -150,7 +150,7 @@
<!-- Show Arguments only if no display_type and not for todo_write -->
<div v-if="event.arguments && event.tool_name !== 'todo_write' && !event.display_type" class="tool-arguments-wrapper">
<div class="arguments-header">
- <span class="arguments-label">参数</span>
+ <span class="arguments-label">{{ $t('agent.argumentsLabel') }}</span>
</div>
<pre class="detail-code">{{ formatJSON(event.arguments) }}</pre>
</div>
@@ -182,10 +182,10 @@
</template>
<template v-else>
<div v-if="floatPopup.knowledgeTitle" class="tip-meta"><strong>{{ floatPopup.knowledgeTitle }}</strong></div>
- <div v-if="floatPopup.loading" class="tip-loading">加载中...</div>
+ <div v-if="floatPopup.loading" class="tip-loading">{{ $t('common.loading') }}</div>
<div v-else-if="floatPopup.error" class="tip-error">{{ floatPopup.error }}</div>
<div v-else class="tip-content" v-html="floatPopup.content"></div>
- <div v-if="floatPopup.chunkId" class="tip-meta">片段ID: {{ floatPopup.chunkId }}</div>
+ <div v-if="floatPopup.chunkId" class="tip-meta">{{ $t('chat.chunkIdLabel') }} {{ floatPopup.chunkId }}</div>
</template>
</div>
</div>
@@ -201,9 +201,11 @@ import ToolResultRenderer from './ToolResultRenderer.vue';
import { getChunkByIdOnly } from '@/api/knowledge-base';
import { MessagePlugin } from 'tdesign-vue-next';
import { useUIStore } from '@/stores/ui';
+import { useI18n } from 'vue-i18n';
const router = useRouter();
const uiStore = useUIStore();
+const { t } = useI18n();
const TOOL_NAME_I18N: Record<string, string> = {
search_knowledge: '知识库检索',
@@ -220,7 +222,7 @@ const TOOL_NAME_I18N: Record<string, string> = {
};
const getLocalizedToolName = (toolName?: string | null): string => {
- if (!toolName) return '工具';
+ if (!toolName) return t('agent.toolFallback');
return TOOL_NAME_I18N[toolName] || toolName;
};
diff --git a/frontend/src/views/chat/components/ToolResultRenderer.vue b/frontend/src/views/chat/components/ToolResultRenderer.vue
index 163d18e2a..feed7d1a1 100644
--- a/frontend/src/views/chat/components/ToolResultRenderer.vue
+++ b/frontend/src/views/chat/components/ToolResultRenderer.vue
@@ -70,7 +70,7 @@
<!-- Fallback: Display raw output -->
<div v-else class="fallback-output">
<div class="fallback-header">
- <span class="fallback-label">原始输出</span>
+ <span class="fallback-label">{{ $t('chat.rawOutputLabel') }}</span>
</div>
<div class="detail-output-wrapper">
<div class="detail-output">{{ output }}</div>
diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue
index 2ad115a55..41cea3c4d 100644
--- a/frontend/src/views/chat/components/botmsg.vue
+++ b/frontend/src/views/chat/components/botmsg.vue
@@ -9,12 +9,12 @@
<div ref="parentMd" v-if="!session.hideContent && !session.isAgentMode">
<!-- 消息正在总结中则渲染加载gif -->
<img v-if="session.thinking" class="botanswer_laoding_gif" src="@/assets/img/botanswer_loading.gif"
- alt="正在总结答案……">
+ :alt="$t('chat.summaryInProgress')">
<!-- 直接渲染完整内容,避免切分导致的问题,样式与 thinking 一致 -->
<div class="content-wrapper">
<div class="ai-markdown-template markdown-content" v-html="processMarkdown(content || session.content)"></div>
</div>
- <div v-if="isImgLoading" class="img_loading"><t-loading size="small"></t-loading><span>加载中...</span></div>
+ <div v-if="isImgLoading" class="img_loading"><t-loading size="small"></t-loading><span>{{ $t('common.loading') }}</span></div>
</div>
<picturePreview :reviewImg="reviewImg" :reviewUrl="reviewUrl" @closePreImg="closePreImg"></picturePreview>
</div>
@@ -27,6 +27,7 @@ import deepThink from './deepThink.vue';
import AgentStreamDisplay from './AgentStreamDisplay.vue';
import picturePreview from '@/components/picture-preview.vue';
import { sanitizeHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL } from '@/utils/security';
+import { useI18n } from 'vue-i18n';
marked.use({
mangle: false,
@@ -34,6 +35,7 @@ marked.use({
breaks: true, // 全局启用单个换行支持
});
const emit = defineEmits(['scroll-bottom'])
+const { t } = useI18n()
const renderer = new marked.Renderer();
let parentMd = ref()
let reviewUrl = ref('')
@@ -116,7 +118,7 @@ const processMarkdown = (markdownText) => {
customRenderer.image = function(href, title, text) {
// 验证图片 URL 是否安全
if (!isValidImageURL(href)) {
- return `<p>无效的图片链接</p>`;
+ return `<p>${t('error.invalidImageLink')}</p>`;
}
// 使用安全的图片创建函数
return createSafeImage(href, text || '', title || '');
diff --git a/frontend/src/views/chat/components/deepThink.vue b/frontend/src/views/chat/components/deepThink.vue
index 36bd149c1..67745dbf6 100644
--- a/frontend/src/views/chat/components/deepThink.vue
+++ b/frontend/src/views/chat/components/deepThink.vue
@@ -11,10 +11,10 @@
<template #header>
<div class="deep-title">
<div v-if="deepSession.thinking" class="thinking">
- <img class="img_gif" src="@/assets/img/think.gif" alt="">思考中···
+ <img class="img_gif" src="@/assets/img/think.gif" :alt="$t('chat.thinkingAlt')">{{ $t('chat.thinking') }}
</div>
<div v-else class="done">
- <img class="icon deep_icon" src="@/assets/img/Frame3718.svg" alt=""></img>已深度思考
+ <img class="icon deep_icon" src="@/assets/img/Frame3718.svg" :alt="$t('chat.deepThoughtAlt')"></img>{{ $t('chat.deepThoughtCompleted') }}
</div>
</div>
</template>
@@ -30,8 +30,10 @@
<script setup>
import { onMounted, watch, computed, ref, reactive, defineProps } from 'vue';
import { sanitizeHTML } from '@/utils/security';
+import { useI18n } from 'vue-i18n';
const isFold = ref(true)
+const { t } = useI18n()
const props = defineProps({
// 必填项
deepSession: {
diff --git a/frontend/src/views/chat/components/docInfo.vue b/frontend/src/views/chat/components/docInfo.vue
index eef1119a8..bb90fe4e8 100644
--- a/frontend/src/views/chat/components/docInfo.vue
+++ b/frontend/src/views/chat/components/docInfo.vue
@@ -2,8 +2,8 @@
<div class="refer">
<div class="refer_header" @click="referBoxSwitch" v-if="session.knowledge_references && session.knowledge_references.length">
<div class="refer_title">
- <img src="@/assets/img/ziliao.svg" alt="" />
- <span>参考了{{ session.knowledge_references && session.knowledge_references.length }}个相关内容</span>
+ <img src="@/assets/img/ziliao.svg" :alt="$t('chat.referenceIconAlt')" />
+ <span>{{ $t('chat.referencesTitle', { count: session.knowledge_references?.length ?? 0 }) }}</span>
</div>
<div class="refer_show_icon">
<t-icon :name="showReferBox ? 'chevron-up' : 'chevron-down'" />
diff --git a/frontend/src/views/chat/components/sendMsg.vue b/frontend/src/views/chat/components/sendMsg.vue
index ab9a8a06e..259bf3943 100644
--- a/frontend/src/views/chat/components/sendMsg.vue
+++ b/frontend/src/views/chat/components/sendMsg.vue
@@ -1,12 +1,14 @@
<template>
<div>
- <t-textarea resize="none" :autosize="false" v-model="value" placeholder="请输入描述文案" name="description" @change="onChange" />
+ <t-textarea resize="none" :autosize="false" v-model="value" :placeholder="$t('chat.enterDescription')" name="description" @change="onChange" />
</div>
</template>
<script setup>
import { onMounted, watch, computed, ref, reactive } from 'vue';
+import { useI18n } from 'vue-i18n';
const value = ref('');
+const { t } = useI18n();
const onChange = (value,e) => {
console.log(value)
}
diff --git a/frontend/src/views/chat/components/tool-results/ChunkDetail.vue b/frontend/src/views/chat/components/tool-results/ChunkDetail.vue
index b7906846c..5a907d3ce 100644
--- a/frontend/src/views/chat/components/tool-results/ChunkDetail.vue
+++ b/frontend/src/views/chat/components/tool-results/ChunkDetail.vue
@@ -2,32 +2,32 @@
<div class="chunk-detail">
<div class="info-section">
<div class="info-field">
- <span class="field-label">片段ID:</span>
+ <span class="field-label">{{ $t('chat.chunkIdLabel') }}</span>
<span class="field-value"><code>{{ data.chunk_id }}</code></span>
</div>
<div class="info-field">
- <span class="field-label">文档ID:</span>
+ <span class="field-label">{{ $t('chat.documentIdLabel') }}</span>
<span class="field-value"><code>{{ data.knowledge_id }}</code></span>
</div>
<div class="info-field">
- <span class="field-label">位置:</span>
- <span class="field-value">第 {{ data.chunk_index }} 个片段</span>
+ <span class="field-label">{{ $t('chat.positionLabel') }}</span>
+ <span class="field-value">{{ $t('chat.chunkPositionValue', { index: data.chunk_index }) }}</span>
</div>
<div v-if="data.content_length" class="info-field">
- <span class="field-label">内容长度:</span>
- <span class="field-value">{{ data.content_length }} 字符</span>
+ <span class="field-label">{{ $t('chat.contentLengthLabelSimple') }}</span>
+ <span class="field-value">{{ $t('chat.lengthChars', { value: data.content_length }) }}</span>
</div>
</div>
<div class="info-section">
- <div class="info-section-title">完整内容</div>
+ <div class="info-section-title">{{ $t('chat.fullContentLabel') }}</div>
<div class="full-content">{{ data.content }}</div>
</div>
<div class="info-section">
<div class="action-buttons">
<button class="action-button" @click="copyToClipboard">
- 📋 复制内容
+ 📋 {{ $t('chat.copyContent') }}
</button>
</div>
</div>
@@ -37,11 +37,14 @@
<script setup lang="ts">
import { defineProps } from 'vue';
import type { ChunkDetailData } from '@/types/tool-results';
+import { useI18n } from 'vue-i18n';
const props = defineProps<{
data: ChunkDetailData;
}>();
+const { t } = useI18n();
+
const copyToClipboard = () => {
if (navigator.clipboard) {
navigator.clipboard.writeText(props.data.content);
diff --git a/frontend/src/views/chat/components/tool-results/ContentPopup.vue b/frontend/src/views/chat/components/tool-results/ContentPopup.vue
index e3a317ecf..ab6af3008 100644
--- a/frontend/src/views/chat/components/tool-results/ContentPopup.vue
+++ b/frontend/src/views/chat/components/tool-results/ContentPopup.vue
@@ -8,11 +8,11 @@
</div>
<div v-if="hasInfo" class="info-section">
<div v-if="chunkId" class="info-field">
- <span class="field-label">片段ID:</span>
+ <span class="field-label">{{ $t('chat.chunkIdLabel') }}</span>
<span class="field-value"><code>{{ chunkId }}</code></span>
</div>
<div v-if="knowledgeId" class="info-field">
- <span class="field-label">文档ID:</span>
+ <span class="field-label">{{ $t('chat.documentIdLabel') }}</span>
<span class="field-value"><code>{{ knowledgeId }}</code></span>
</div>
</div>
diff --git a/frontend/src/views/chat/components/tool-results/DatabaseQuery.vue b/frontend/src/views/chat/components/tool-results/DatabaseQuery.vue
index c21b21ed4..a5461eba7 100644
--- a/frontend/src/views/chat/components/tool-results/DatabaseQuery.vue
+++ b/frontend/src/views/chat/components/tool-results/DatabaseQuery.vue
@@ -2,14 +2,14 @@
<div class="database-query-display">
<!-- Query Display -->
<div v-if="data.query" class="query-section">
- <div class="section-header">执行的 SQL 查询:</div>
+ <div class="section-header">{{ $t('chat.sqlQueryExecuted') }}</div>
<pre class="query-code">{{ data.query }}</pre>
</div>
<!-- Results Summary -->
<div class="results-summary">
- <strong>返回结果:</strong> {{ data.row_count }} 行
- <span v-if="data.columns"> × {{ data.columns.length }} 列</span>
+ <strong>{{ $t('chat.sqlResultsLabel') }}</strong> {{ data.row_count }} {{ $t('chat.rowsLabel') }}
+ <span v-if="data.columns"> × {{ data.columns.length }} {{ $t('chat.columnsLabel') }}</span>
</div>
<!-- Results Table -->
@@ -32,23 +32,25 @@
<!-- No Results -->
<div v-else class="no-results">
- 未找到匹配的记录
+ {{ $t('chat.noDatabaseRecords') }}
</div>
</div>
</template>
<script setup lang="ts">
import type { DatabaseQueryData } from '@/types/tool-results';
+import { useI18n } from 'vue-i18n';
interface Props {
data: DatabaseQueryData;
}
const props = defineProps<Props>();
+const { t } = useI18n();
const formatValue = (value: any): string => {
if (value === null || value === undefined) {
- return '<NULL>';
+ return t('chat.nullValuePlaceholder');
}
if (typeof value === 'object') {
return JSON.stringify(value);
diff --git a/frontend/src/views/chat/components/tool-results/DocumentInfo.vue b/frontend/src/views/chat/components/tool-results/DocumentInfo.vue
index 208a5026d..db296ec19 100644
--- a/frontend/src/views/chat/components/tool-results/DocumentInfo.vue
+++ b/frontend/src/views/chat/components/tool-results/DocumentInfo.vue
@@ -3,25 +3,25 @@
<div class="info-card">
<div class="info-section">
<div class="info-field">
- <span class="field-label">文档ID:</span>
+ <span class="field-label">{{ $t('chat.documentIdLabel') }}</span>
<span class="field-value"><code>{{ data.knowledge_id }}</code></span>
</div>
<div class="info-field">
- <span class="field-label">文档标题:</span>
+ <span class="field-label">{{ $t('chat.documentTitleLabel') }}</span>
<span class="field-value">{{ data.title }}</span>
</div>
<div class="info-field">
- <span class="field-label">片段数量:</span>
- <span class="field-value">至少 {{ data.chunk_count_min }} 个</span>
+ <span class="field-label">{{ $t('chat.chunkCountLabel') }}</span>
+ <span class="field-value">{{ $t('chat.chunkCountValue', { count: data.chunk_count_min }) }}</span>
</div>
</div>
<div class="status-section">
- <div class="status-title">状态说明</div>
+ <div class="status-title">{{ $t('chat.statusDescription') }}</div>
<div class="status-list">
- <div class="status-item">✓ 文档已索引并可搜索</div>
- <div class="status-item">✓ 可使用搜索工具查找文档内容</div>
- <div class="status-item">✓ 可使用 get_chunk_detail 查看片段详情</div>
+ <div class="status-item">✓ {{ $t('chat.statusIndexed') }}</div>
+ <div class="status-item">✓ {{ $t('chat.statusSearchable') }}</div>
+ <div class="status-item">✓ {{ $t('chat.statusChunkDetailAvailable') }}</div>
</div>
</div>
</div>
diff --git a/frontend/src/views/chat/components/tool-results/GraphQueryResults.vue b/frontend/src/views/chat/components/tool-results/GraphQueryResults.vue
index 9ed66ff43..8e31775ed 100644
--- a/frontend/src/views/chat/components/tool-results/GraphQueryResults.vue
+++ b/frontend/src/views/chat/components/tool-results/GraphQueryResults.vue
@@ -2,13 +2,13 @@
<div class="graph-query-results">
<!-- Graph Configuration Card -->
<div v-if="data.graph_config" class="stats-card">
- <div class="stats-title">图谱配置</div>
+ <div class="stats-title">{{ $t('chat.graphConfigTitle') }}</div>
<div class="info-field">
- <span class="field-label">实体类型:</span>
+ <span class="field-label">{{ $t('chat.entityTypesLabel') }}</span>
<span class="field-value">{{ data.graph_config.nodes.join(', ') }}</span>
</div>
<div class="info-field">
- <span class="field-label">关系类型:</span>
+ <span class="field-label">{{ $t('chat.relationTypesLabel') }}</span>
<span class="field-value">{{ data.graph_config.relations.join(', ') }}</span>
</div>
</div>
@@ -16,7 +16,7 @@
<!-- Results List -->
<div v-if="data.results && data.results.length > 0" class="results-list">
<div class="results-header">
- 找到 {{ data.count }} 条相关结果
+ {{ $t('chat.graphResultsHeader', { count: data.count }) }}
</div>
<div
@@ -28,7 +28,7 @@
<div class="result-title">
<span class="result-index">#{{ result.result_index }}</span>
<span class="relevance-badge" :class="getRelevanceClass(result.relevance_level)">
- {{ result.relevance_level }}
+ {{ getRelevanceLabel(result.relevance_level) }}
</span>
<span class="knowledge-title">{{ result.knowledge_title }}</span>
</div>
@@ -47,7 +47,7 @@
</div>
<div v-else class="empty-state">
- 未找到相关的图谱信息
+ {{ $t('chat.graphNoResults') }}
</div>
</div>
</template>
@@ -55,11 +55,14 @@
<script setup lang="ts">
import { ref, defineProps } from 'vue';
import type { GraphQueryResultsData, RelevanceLevel } from '@/types/tool-results';
+import { useI18n } from 'vue-i18n';
const props = defineProps<{
data: GraphQueryResultsData;
}>();
+const { t } = useI18n();
+
const expandedResults = ref<string[]>([]);
const toggleResult = (chunkId: string) => {
@@ -80,6 +83,16 @@ const getRelevanceClass = (level: RelevanceLevel): string => {
};
return classMap[level] || 'weak';
};
+
+const getRelevanceLabel = (level: RelevanceLevel): string => {
+ const labelMap: Record<RelevanceLevel, string> = {
+ '高相关': t('chat.relevanceHigh'),
+ '中相关': t('chat.relevanceMedium'),
+ '低相关': t('chat.relevanceLow'),
+ '弱相关': t('chat.relevanceWeak'),
+ };
+ return labelMap[level] || level;
+};
</script>
<style lang="less" scoped>
diff --git a/frontend/src/views/chat/components/tool-results/KnowledgeBaseList.vue b/frontend/src/views/chat/components/tool-results/KnowledgeBaseList.vue
index 521d29221..e7786b365 100644
--- a/frontend/src/views/chat/components/tool-results/KnowledgeBaseList.vue
+++ b/frontend/src/views/chat/components/tool-results/KnowledgeBaseList.vue
@@ -2,7 +2,7 @@
<div class="knowledge-base-list">
<div v-if="data.knowledge_bases && data.knowledge_bases.length > 0">
<div class="stats-card">
- <div class="stats-title">共 {{ data.count }} 个知识库</div>
+ <div class="stats-title">{{ $t('chat.knowledgeBaseCount', { count: data.count }) }}</div>
</div>
<div class="card-grid">
@@ -29,7 +29,7 @@
</div>
<div v-else class="empty-state">
- 没有可用的知识库
+ {{ $t('chat.noKnowledgeBases') }}
</div>
</div>
</template>
diff --git a/frontend/src/views/chat/components/tool-results/PlanDisplay.vue b/frontend/src/views/chat/components/tool-results/PlanDisplay.vue
index 18c4c28d8..c7dde962e 100644
--- a/frontend/src/views/chat/components/tool-results/PlanDisplay.vue
+++ b/frontend/src/views/chat/components/tool-results/PlanDisplay.vue
@@ -19,7 +19,7 @@
</div>
<div v-else class="no-steps">
- 未提供具体步骤
+ {{ $t('chat.noPlanSteps') }}
</div>
</div>
</template>
diff --git a/frontend/src/views/chat/components/tool-results/RelatedChunks.vue b/frontend/src/views/chat/components/tool-results/RelatedChunks.vue
index a1bae7223..3ff43caf8 100644
--- a/frontend/src/views/chat/components/tool-results/RelatedChunks.vue
+++ b/frontend/src/views/chat/components/tool-results/RelatedChunks.vue
@@ -22,8 +22,8 @@
</template>
<div class="result-header">
<div class="result-title">
- <span class="chunk-index">片段 #{{ chunk.index }}</span>
- <span class="chunk-position">(位置: {{ chunk.chunk_index }})</span>
+ <span class="chunk-index">{{ $t('chat.chunkIndexLabel', { index: chunk.index }) }}</span>
+ <span class="chunk-position">{{ $t('chat.chunkPositionLabel', { position: chunk.chunk_index }) }}</span>
</div>
</div>
</t-popup>
@@ -31,7 +31,7 @@
</div>
<div v-else class="empty-state">
- 没有找到相关片段
+ {{ $t('chat.noRelatedChunks') }}
</div>
</div>
</template>
diff --git a/frontend/src/views/chat/components/tool-results/SearchResults.vue b/frontend/src/views/chat/components/tool-results/SearchResults.vue
index 7269df1ca..62022fb2f 100644
--- a/frontend/src/views/chat/components/tool-results/SearchResults.vue
+++ b/frontend/src/views/chat/components/tool-results/SearchResults.vue
@@ -26,7 +26,7 @@
<div class="result-title">
<span class="result-index">#{{ result.result_index }}</span>
<span class="relevance-badge" :class="getRelevanceClass(result.relevance_level)">
- {{ result.relevance_level }}
+ {{ getRelevanceLabel(result.relevance_level) }}
</span>
<span class="knowledge-title">{{ result.knowledge_title }}</span>
</div>
@@ -37,7 +37,7 @@
<!-- Empty State -->
<div v-else class="empty-state">
- 没有找到搜索结果
+ {{ $t('chat.noSearchResults') }}
</div>
</div>
</template>
@@ -47,12 +47,15 @@ import { ref, defineProps, computed } from 'vue';
import type { SearchResultsData, SearchResultItem, RelevanceLevel } from '@/types/tool-results';
import { getMatchTypeIcon } from '@/utils/tool-icons';
import ContentPopup from './ContentPopup.vue';
+import { useI18n } from 'vue-i18n';
const props = defineProps<{
data: SearchResultsData;
arguments?: Record<string, any> | string;
}>();
+const { t } = useI18n();
+
const results = computed(() => props.data.results || []);
const kbCounts = computed(() => props.data.kb_counts);
@@ -105,6 +108,16 @@ const getRelevanceClass = (level: RelevanceLevel): string => {
};
return classMap[level] || 'weak';
};
+
+const getRelevanceLabel = (level: RelevanceLevel): string => {
+ const labelMap: Record<RelevanceLevel, string> = {
+ '高相关': t('chat.relevanceHigh'),
+ '中相关': t('chat.relevanceMedium'),
+ '低相关': t('chat.relevanceLow'),
+ '弱相关': t('chat.relevanceWeak'),
+ };
+ return labelMap[level] || level;
+};
</script>
<style lang="less" scoped>
diff --git a/frontend/src/views/chat/components/tool-results/ThinkingDisplay.vue b/frontend/src/views/chat/components/tool-results/ThinkingDisplay.vue
index 2f03dd79d..1798aa660 100644
--- a/frontend/src/views/chat/components/tool-results/ThinkingDisplay.vue
+++ b/frontend/src/views/chat/components/tool-results/ThinkingDisplay.vue
@@ -1,7 +1,7 @@
<template>
<div class="thinking-display">
<div class="thinking-content">
- <div class="thinking-icon">💭</div>
+ <div class="thinking-icon" aria-hidden="true">💭</div>
<div class="thinking-text">{{ data.thought }}</div>
</div>
</div>
@@ -10,10 +10,13 @@
<script setup lang="ts">
import { defineProps } from 'vue';
import type { ThinkingData } from '@/types/tool-results';
+import { useI18n } from 'vue-i18n';
const props = defineProps<{
data: ThinkingData;
}>();
+
+useI18n(); // ensure component reacts to locale changes if needed
</script>
<style lang="less" scoped>
diff --git a/frontend/src/views/chat/components/tool-results/WebFetchResults.vue b/frontend/src/views/chat/components/tool-results/WebFetchResults.vue
index feac91e8e..3d9a1450f 100644
--- a/frontend/src/views/chat/components/tool-results/WebFetchResults.vue
+++ b/frontend/src/views/chat/components/tool-results/WebFetchResults.vue
@@ -19,11 +19,11 @@
>
<span class="result-domain">{{ safeHostname(item.url) }}</span>
</a>
- <span v-else class="result-domain">未知链接</span>
+ <span v-else class="result-domain">{{ $t('chat.unknownLink') }}</span>
</div>
<div class="result-meta">
<span v-if="item.method" class="meta-pill">{{ formatMethod(item.method) }}</span>
- <span v-if="item.content_length" class="meta-text">长度 {{ formatLength(item.content_length) }}</span>
+ <span v-if="item.content_length" class="meta-text">{{ $t('chat.contentLengthLabel', { value: formatLength(item.content_length) }) }}</span>
<t-icon
:name="isExpanded(index) ? 'chevron-up' : 'chevron-down'"
class="expand-icon"
@@ -42,29 +42,29 @@
target="_blank"
rel="noopener noreferrer"
>{{ item.url }}</a>
- <span v-else>未提供</span>
+ <span v-else>{{ $t('chat.notProvided') }}</span>
</span>
</div>
<div v-if="item.prompt" class="info-field">
- <span class="field-label">提示词</span>
+ <span class="field-label">{{ $t('chat.promptLabel') }}</span>
<span class="field-value">{{ item.prompt }}</span>
</div>
</div>
<div v-if="item.error" class="info-section">
- <div class="info-section-title error">错误信息</div>
+ <div class="info-section-title error">{{ $t('chat.errorMessageLabel') }}</div>
<div class="full-content error-text">{{ item.error }}</div>
</div>
<div v-else>
<div v-if="item.summary" class="info-section">
- <div class="info-section-title">总结</div>
+ <div class="info-section-title">{{ $t('chat.summaryLabel') }}</div>
<div class="full-content">{{ item.summary }}</div>
</div>
<div v-if="item.raw_content" class="info-section">
<div class="info-section-title">
- 原始文本
+ {{ $t('chat.rawTextLabel') }}
<span class="raw-length" v-if="item.content_length">
({{ formatLength(item.content_length) }})
</span>
@@ -76,7 +76,7 @@
{{ truncate(item.raw_content) }}
</div>
<button class="action-button" @click.stop="toggleRaw(index)">
- {{ isRawExpanded(index) ? '收起原文' : '展开原文' }}
+ {{ isRawExpanded(index) ? $t('chat.collapseRaw') : $t('chat.expandRaw') }}
</button>
</div>
</div>
@@ -84,19 +84,21 @@
</div>
</div>
- <div v-else class="empty-state">未获取到网页内容</div>
+ <div v-else class="empty-state">{{ $t('chat.noWebContent') }}</div>
</div>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import type { WebFetchResultsData, WebFetchResultItem } from '@/types/tool-results';
+import { useI18n } from 'vue-i18n';
interface Props {
data: WebFetchResultsData;
}
const props = defineProps<Props>();
+const { t } = useI18n();
const items = computed<WebFetchResultItem[]>(() => props.data.results || []);
const expandedCards = ref<Set<number>>(new Set());
@@ -147,14 +149,14 @@ const safeHostname = (url: string): string => {
};
const formatLength = (length: number): string => {
- if (!length || Number.isNaN(length)) return '0';
+ if (!length || Number.isNaN(length)) return t('chat.lengthChars', { value: 0 });
if (length >= 10000) {
- return `${(length / 10000).toFixed(1)} 万字`;
+ return t('chat.lengthTenThousands', { value: (length / 10000).toFixed(1) });
}
if (length >= 1000) {
- return `${(length / 1000).toFixed(1)} 千字`;
+ return t('chat.lengthThousands', { value: (length / 1000).toFixed(1) });
}
- return `${length} 字`;
+ return t('chat.lengthChars', { value: length });
};
const formatMethod = (method: string): string => {
diff --git a/frontend/src/views/chat/components/tool-results/WebSearchResults.vue b/frontend/src/views/chat/components/tool-results/WebSearchResults.vue
index 886313859..50d4d9d11 100644
--- a/frontend/src/views/chat/components/tool-results/WebSearchResults.vue
+++ b/frontend/src/views/chat/components/tool-results/WebSearchResults.vue
@@ -8,7 +8,7 @@
class="results-group"
>
<!-- <div class="group-header">
- <span class="group-intro">以下 {{ group.items.length }} 条内容来自</span>
+ <span class="group-intro">{{ $t('chat.webGroupIntro', { count: group.items.length }) }}</span>
<span class="group-source">{{ group.label }}</span>
</div> -->
<div class="results-list">
@@ -47,7 +47,7 @@
<!-- Empty State -->
<div v-else class="empty-state">
- 未找到搜索结果
+ {{ $t('chat.webSearchNoResults') }}
</div>
</div>
</template>
@@ -55,12 +55,14 @@
<script setup lang="ts">
import { computed } from 'vue';
import type { WebSearchResultsData, WebSearchResultItem } from '@/types/tool-results';
+import { useI18n } from 'vue-i18n';
interface Props {
data: WebSearchResultsData;
}
const props = defineProps<Props>();
+const { t, locale } = useI18n();
const results = computed(() => props.data.results || []);
@@ -79,7 +81,7 @@ const groupedResults = computed<Group[]>(() => {
} else {
// fallback to domain
const url = (item as any).url as string | undefined;
- const hostname = url ? safeHostname(url) : '其他';
+ const hostname = url ? safeHostname(url) : t('chat.otherSource');
key = `dom:${hostname}`;
label = hostname;
}
@@ -94,7 +96,7 @@ const groupedResults = computed<Group[]>(() => {
for (const item of list) {
const source = (item as any).source as string | undefined;
const url = (item as any).url as string | undefined;
- const hostname = url ? safeHostname(url) : '其他';
+ const hostname = url ? safeHostname(url) : t('chat.otherSource');
const key = source && source.trim() ? `src:${source.trim()}` : `dom:${hostname}`;
if (!seen.has(key)) {
seen.add(key);
@@ -118,7 +120,7 @@ const safeHostname = (url: string): string => {
const urlObj = new URL(url);
return urlObj.hostname;
} catch {
- return '其他';
+ return t('chat.otherSource');
}
};
@@ -131,7 +133,7 @@ const truncateContent = (content: string, maxLength: number = 300): string => {
const formatDate = (dateStr: string): string => {
try {
const date = new Date(dateStr);
- return date.toLocaleDateString('zh-CN', {
+ return date.toLocaleDateString(locale.value || 'zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric'
diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue
index 01cbb9614..bc3db333f 100644
--- a/frontend/src/views/chat/index.vue
+++ b/frontend/src/views/chat/index.vue
@@ -13,7 +13,7 @@
</div>
<div v-if="loading"
style="height: 41px;display: flex;align-items: center;background: #fff;width: 58px;">
- <img class="botanswer_laoding_gif" src="@/assets/img/botanswer_loading.gif" alt="正在等待答案……">
+ <img class="botanswer_laoding_gif" src="@/assets/img/botanswer_loading.gif" :alt="$t('chat.waitingForAnswer')">
</div>
</div>
</div>
@@ -40,8 +40,10 @@ import { useStream } from '../../api/chat/streame'
import { useMenuStore } from '@/stores/menu';
import { useSettingsStore } from '@/stores/settings';
import { MessagePlugin } from 'tdesign-vue-next';
+import { useI18n } from 'vue-i18n';
const usemenuStore = useMenuStore();
const useSettingsStoreInstance = useSettingsStore();
+const { t } = useI18n();
const { menuArr, isFirstSession, firstQuery } = storeToRefs(usemenuStore);
const { output, onChunk, isStreaming, isLoading, error, startStream, stopStream } = useStream();
const route = useRoute();
@@ -233,7 +235,7 @@ const handleMsgList = async (data, isScrollType = false, newScrollHeight) => {
// 只给非Agent模式的空内容已完成消息设置默认错误消息
// Agent模式的消息内容在agent_steps中,content为空是正常的
if (item.is_completed && !item.content && !item.isAgentMode) {
- item.content = "抱歉,我无法回答这个问题。";
+ item.content = t('chat.cannotAnswer');
}
messagesList.unshift(item);
if (isFirstEnter.value) {
@@ -292,7 +294,7 @@ const sendMsg = async (value, modelId = '') => {
// Validate knowledge_base_ids before sending (only when agent mode is enabled)
if (agentEnabled && kbIds.length === 0) {
- MessagePlugin.warning('请至少选择一个知识库');
+ MessagePlugin.warning(t('chat.selectKnowledgeBaseWarning'));
isReplying.value = false;
loading.value = false;
// 清空当前 assistant message ID
@@ -651,12 +653,12 @@ const handleAgentChunk = (data) => {
// If this is an error response without tool data, handle it
if (data.response_type === 'error' && !toolName) {
- message.content = data.content || '处理出错';
+ message.content = data.content || t('chat.processError');
isReplying.value = false;
}
} else if (data.response_type === 'error') {
// Generic error without tool context
- message.content = data.content || '处理出错';
+ message.content = data.content || t('chat.processError');
isReplying.value = false;
}
break;
diff --git a/frontend/src/views/creatChat/creatChat.vue b/frontend/src/views/creatChat/creatChat.vue
index a6b1fb9cd..fbba05a8d 100644
--- a/frontend/src/views/creatChat/creatChat.vue
+++ b/frontend/src/views/creatChat/creatChat.vue
@@ -2,7 +2,7 @@
<div class="dialogue-wrap">
<div class="dialogue-answers">
<div class="dialogue-title">
- <span>基于知识库内容问答 - AI 问答</span>
+ <span>{{ $t('createChat.title') }}</span>
</div>
<InputField @send-msg="sendMsg"></InputField>
</div>
@@ -16,11 +16,13 @@ import { useMenuStore } from '@/stores/menu';
import { useSettingsStore } from '@/stores/settings';
import { useRoute, useRouter } from 'vue-router';
import { MessagePlugin } from 'tdesign-vue-next';
+import { useI18n } from 'vue-i18n';
const router = useRouter();
const route = useRoute();
const usemenuStore = useMenuStore();
const settingsStore = useSettingsStore();
+const { t } = useI18n();
const sendMsg = (value: string) => {
createNewSession(value);
@@ -30,7 +32,7 @@ async function createNewSession(value: string) {
const selectedKbs = settingsStore.settings.selectedKnowledgeBases;
if (!selectedKbs || selectedKbs.length === 0) {
- MessagePlugin.warning('请先选择知识库');
+ MessagePlugin.warning(t('createChat.messages.selectKnowledgeBase'));
return;
}
@@ -52,19 +54,19 @@ async function createNewSession(value: string) {
if (res.data && res.data.id) {
await navigateToSession(res.data.id, value);
} else {
- console.error("创建会话失败");
- MessagePlugin.error("创建会话失败");
+ console.error('[createChat] Failed to create session');
+ MessagePlugin.error(t('createChat.messages.createFailed'));
}
} catch (error) {
- console.error("创建会话出错:", error);
- MessagePlugin.error("创建会话失败,请稍后重试");
+ console.error('[createChat] Create session error:', error);
+ MessagePlugin.error(t('createChat.messages.createError'));
}
}
const navigateToSession = async (sessionId: string, value: string) => {
const now = new Date().toISOString();
let obj = {
- title: '新会话',
+ title: t('createChat.newSessionTitle'),
path: `chat/${sessionId}`,
id: sessionId,
isMore: false,
diff --git a/frontend/src/views/initialization/InitializationContent.vue b/frontend/src/views/initialization/InitializationContent.vue
deleted file mode 100644
index 2e9196162..000000000
--- a/frontend/src/views/initialization/InitializationContent.vue
+++ /dev/null
@@ -1,3804 +0,0 @@
-<template>
- <div class="settings-page-container">
- <div class="initialization-content">
- <!-- 顶部Ollama服务状态 -->
- <div class="ollama-summary-card">
- <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">
- <!-- 知识库基本信息配置区域 (仅在知识库设置模式下显示) -->
- <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>
- <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')"
- :clearable="!modelStatus.llm.downloading" />
- <div class="model-status-icon">
- <!-- 下载状态:优先显示 -->
- <div v-if="formData.llm.source === 'local' && formData.llm.modelName && modelStatus.llm.downloading" class="model-download-status">
- <span class="download-percentage">{{ modelStatus.llm.progress.toFixed(1) }}%</span>
- </div>
- <!-- 其他状态:非下载时显示 -->
- <t-icon
- v-else-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="未检查"
- />
- </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>
-
- <!-- 远程 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">
- <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"
- :clearable="!modelStatus.embedding.downloading" />
- <div class="model-status-icon">
- <!-- 下载状态:优先显示 -->
- <div v-if="formData.embedding.source === 'local' && formData.embedding.modelName && modelStatus.embedding.downloading" class="model-download-status">
- <span class="download-percentage">{{ modelStatus.embedding.progress.toFixed(1) }}%</span>
- </div>
- <!-- 其他状态:非下载时显示 -->
- <t-icon
- v-else-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="未检查"
- />
- </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>
-
- <!-- 远程 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">
- <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 id="multimodal-config-section" class="config-section">
- <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')"
- :clearable="!modelStatus.vlm.downloading" />
- <div class="model-status-icon">
- <!-- 下载状态:优先显示环形进度条 -->
- <div v-if="formData.multimodal.vlm.interfaceType === 'ollama' && formData.multimodal.vlm.modelName && modelStatus.vlm.downloading" class="model-download-status">
- <span class="download-percentage">{{ modelStatus.vlm.progress.toFixed(1) }}%</span>
- </div>
- <!-- 其他状态:非下载时显示 -->
- <t-icon
- v-else-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="未检查"
- />
- </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>
- <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.multimodal.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.multimodal.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.multimodal.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.multimodal.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.multimodal.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.multimodal.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.multimodal.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.multimodal.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">
- <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="config-section">
- <h3><t-icon name="transform" class="section-icon" />实体关系提取</h3>
-
- <div class="form-row">
- <t-form-item name="nodeExtract.enabled">
- <div class="switch-container">
- <t-switch v-model="formData.nodeExtract.enabled" @change="clearExtractExample" />
- <span class="switch-label">启用实体关系提取</span>
- </div>
- </t-form-item>
- </div>
-
- <div v-if="formData.nodeExtract.enabled" class="node-config">
- <h4>关系标签配置</h4>
- <!-- 关系标签配置区域 -->
- <div class="form-row">
- <t-form-item label="关系类型" name="tags">
- <div class="tags-grid">
- <div class="btn-tips-form">
- <div class="tags-gen-btn">
- <t-button
- theme="default"
- size="medium"
- :disabled="!modelStatus.llm.available"
- :loading="tagFabring"
- @click="handleFabriTag"
- class="gen-tags-btn"
- >
- 随机生成标签
- </t-button>
- </div>
- <div v-if="!modelStatus.llm.available" class="btn-tips">
- <t-icon name="info-circle" class="tip-icon" />
- <span>请完善模型配置信息</span>
- </div>
- </div>
- <div class="tags-config">
- <t-select
- v-model="formData.nodeExtract.tags"
- v-model:input-value="tagInput"
- multiple
- placeholder="系统将根据选定的关系类型从文本中提取相应的实体关系"
- :options="tagOptions"
- clearable
- @clear="clearTags"
- creatable
- @create="addTag"
- filterable
- />
- </div>
- </div>
- </t-form-item>
- </div>
-
- <h4>提取示例</h4>
- <!-- 文本内容输入区域 -->
- <div class="form-row">
- <t-form-item label="示例文本" name="text" :required="true">
- <div class="sample-text-form">
- <div class="btn-tips-form">
- <div class="tags-gen-btn">
- <t-button
- theme="default"
- size="medium"
- :disabled="!modelStatus.llm.available"
- :title="!modelStatus.llm.available ? 'LLM 模型不可用' : ''"
- :loading="textFabring"
- @click="handleFabriText"
- class="tags-gen-btn"
- >
- 随机生成文本
- </t-button>
- </div>
- <div v-if="!modelStatus.llm.available" class="btn-tips">
- <t-icon name="info-circle" class="tip-icon" />
- <span>请完善模型配置信息</span>
- </div>
- </div>
- <div class="sample-text">
- <t-textarea
- v-model="formData.nodeExtract.text"
- placeholder="请输入需要分析的文本内容,例如:《红楼梦》,又名《石头记》,是清代作家曹雪芹创作的中国古典四大名著之一..."
- :autosize="{ minRows: 8, maxRows: 15 }"
- show-word-limit
- maxlength="5000"
- />
- </div>
- </div>
- </t-form-item>
- </div>
-
- <!-- 提取实体 -->
- <div class="form-row">
- <!-- 实体列表 -->
- <t-form-item v-if="formData.nodeExtract.nodes.length > 0" label="实体列表" name="node-form">
- <div class="node-list">
- <div v-for="(node, nodeIndex) in formData.nodeExtract.nodes" :key="nodeIndex" class="node-item">
- <div class="node-header">
- <span class="node-icon"><t-icon name="user" class="node-icon-svg" /></span>
- <!-- 节点名称输入 -->
- <t-input
- type="text"
- v-model="node.name"
- class="node-name-input"
- placeholder="节点名称"
- />
- <!-- 删除节点按钮 -->
- <t-button
- class="delete-node-btn"
- theme="default"
- @click="removeNode(nodeIndex)"
- :disabled="formData.nodeExtract.nodes.length === 0"
- size="small"
- >
- <t-icon name="delete" />
- </t-button>
- </div>
-
- <div class="node-attributes">
- <!-- 属性列表 -->
- <div v-for="(attribute, attrIndex) in node.attributes" :key="attrIndex" class="attribute-item">
- <t-input
- type="text"
- v-model="node.attributes[attrIndex]"
- class="attribute-input"
- placeholder="属性值"
- />
- <t-button
- class="delete-attr-btn"
- theme="default"
- @click="removeAttribute(nodeIndex, attrIndex)"
- :disabled="node.attributes.length === 0"
- size="small"
- >
- <t-icon name="close" />
- </t-button>
- </div>
-
- <!-- 添加属性按钮 -->
- <t-button class="add-attr-btn" @click="addAttribute(nodeIndex)" size="small">
- 添加属性
- </t-button>
- </div>
- </div>
- </div>
- </t-form-item>
- <!-- 添加实体按钮 -->
- <div class="btn-tips-form">
- <div class="tags-gen-btn">
- <t-button class="add-node-btn" @click="addNode">
- 添加实体
- </t-button>
- </div>
- <div v-if="!readyNode" class="btn-tips">
- <t-icon name="info-circle" class="tip-icon" />
- <span>请完善实体信息</span>
- </div>
- </div>
- </div>
-
- <!-- 提取关系 -->
- <div class="form-row">
- <t-form-item v-if="formData.nodeExtract.relations.length > 0" label="关系连接" name="node-relation">
- <div class="relation-list">
- <div v-for="(relation, index) in formData.nodeExtract.relations" :key="index" class="relation-item">
- <div class="relation-line">
- <t-select-input
- :value="formData.nodeExtract.relations[index].node1"
- :popup-visible="popupVisibleNode1[index]"
- placeholder="请选择实体"
- clearable
- @popup-visible-change="onPopupVisibleNode1Change(index, $event)"
- @clear="relationOnClearNode1(index)"
- @focus="onFocus"
- >
- <template #panel>
- <ul class="select-input-node">
- <li v-for="item in formData.nodeExtract.nodes" :key="item.name" @click="onRelationNode1OptionClick(index, item)">
- {{ item.name }}
- </li>
- </ul>
- </template>
- <template #suffixIcon>
- <ChevronDownIcon />
- </template>
- </t-select-input>
- <t-icon name="arrow-right" class="relation-arrow"/>
- <t-select
- v-model="formData.nodeExtract.relations[index].type"
- placeholder="请选择关系类型"
- :options="tagOptions"
- clearable
- creatable
- filterable
- />
- <t-icon name="arrow-right" class="relation-arrow"/>
- <t-select-input
- :value="formData.nodeExtract.relations[index].node2"
- :popup-visible="popupVisibleNode2[index]"
- placeholder="请选择实体"
- clearable
- @popup-visible-change="onPopupVisibleNode2Change(index, $event)"
- @clear="relationOnClearNode2(index)"
- @focus="onFocus"
- >
- <template #panel>
- <ul class="select-input-node">
- <li v-for="item in formData.nodeExtract.nodes" :key="item.name" @click="onRelationNode2OptionClick(index, item)">
- {{ item.name }}
- </li>
- </ul>
- </template>
- <template #suffixIcon>
- <ChevronDownIcon />
- </template>
- </t-select-input>
- <t-button
- class="delete-node-btn"
- theme="default"
- @click="removeRelation(index)"
- :disabled="formData.nodeExtract.relations.length === 0"
- size="small"
- >
- <t-icon name="delete" />
- </t-button>
- </div>
- </div>
- </div>
- </t-form-item>
-
- <!-- 添加关系按钮 -->
- <div class="btn-tips-form">
- <div class="tags-gen-btn">
- <t-button class="add-node-btn" @click="addRelation">
- 添加关系
- </t-button>
- </div>
- <div v-if="!readyRelation" class="btn-tips">
- <t-icon name="info-circle" class="tip-icon" />
- <span>请完善关系信息</span>
- </div>
- </div>
- </div>
-
- <!-- 重置按钮区域 -->
- <div class="extract-button">
- <t-button
- theme="primary"
- size="medium"
- :disabled="!modelStatus.llm.available"
- :title="!modelStatus.llm.available ? 'LLM 模型不可用' : ''"
- :loading="extracting"
- @click="handleExtract"
- >
- {{ extracting ? '正在提取...' : '开始提取' }}
- </t-button>
-
- <t-button
- theme="default"
- size="medium"
- @click="defaultExtractExample"
- class="default-extract-btn"
- >
- 默认示例
- </t-button>
-
- <t-button
- theme="default"
- size="medium"
- @click="clearExtractExample"
- class="clear-extract-btn"
- >
- 清空示例
- </t-button>
- </div>
- </div>
- </div>
-
- <!-- Agent 智能问答配置区域 -->
- <div class="config-section">
- <h3>
- <t-icon name="service" class="section-icon" />Agent 智能问答配置
- <t-tag v-if="formData.agent.enabled" theme="success" size="small" style="margin-left: 8px">已启用</t-tag>
- <t-tag v-else theme="default" size="small" style="margin-left: 8px">未启用</t-tag>
- </h3>
-
- <div class="form-row">
- <t-form-item name="agent.enabled">
- <div class="checkbox-with-label">
- <t-switch v-model="formData.agent.enabled" size="large">
- <template #label="slotProps">
- {{ slotProps.value ? '已启用' : '已禁用' }}
- </template>
- </t-switch>
- <div class="help-text" style="margin-left: 16px">
- 启用 Agent 模式,通过 ReAct 推理框架回答复杂问题
- <t-button variant="text" size="small" @click="showAgentHelp = true">
- 了解更多
- </t-button>
- </div>
- </div>
- </t-form-item>
- </div>
-
- <!-- Agent 详细配置(启用后显示) -->
- <div v-if="formData.agent.enabled" class="agent-detail-config">
- <div class="form-row">
- <t-form-item label="最大推理步数" name="agent.maxIterations">
- <t-input-number
- v-model="formData.agent.maxIterations"
- :min="1"
- :max="20"
- style="width: 200px;"
- />
- <div class="field-description">Agent 最多执行多少步推理,建议 5-10 步</div>
- </t-form-item>
- </div>
-
- <div class="form-row">
- <t-form-item label="温度参数" name="agent.temperature">
- <t-slider
- v-model="formData.agent.temperature"
- :min="0"
- :max="1"
- :step="0.1"
- :marks="{ 0: '精确', 0.5: '平衡', 1: '创造' }"
- style="width: 400px;"
- />
- <div class="field-description">控制回答的随机性,0=更精确,1=更有创造性</div>
- </t-form-item>
- </div>
-
- <div class="form-row">
- <t-form-item label="思考模型ID" name="agent.thinkingModelId">
- <t-input
- v-model="formData.agent.thinkingModelId"
- placeholder="留空使用默认 LLM 模型"
- style="width: 400px;"
- />
- <div class="field-description">指定用于 Agent 推理的模型 ID</div>
- </t-form-item>
- </div>
-
- <div class="form-row">
- <t-form-item label="允许的工具" name="agent.allowedTools">
- <t-checkbox-group v-model="formData.agent.allowedTools">
- <t-checkbox value="knowledge_search">知识库检索</t-checkbox>
- <t-checkbox value="multi_kb_search">多知识库检索</t-checkbox>
- <t-checkbox value="list_knowledge_bases">列出知识库</t-checkbox>
- <t-checkbox value="get_chunk_detail">获取文档块详情</t-checkbox>
- <t-checkbox value="get_related_chunks">获取相关文档块</t-checkbox>
- <t-checkbox value="query_knowledge_graph">查询知识图谱</t-checkbox>
- <t-checkbox value="get_document_info">获取文档信息</t-checkbox>
- </t-checkbox-group>
- <div class="field-description">选择 Agent 可以使用的工具</div>
- </t-form-item>
- </div>
- </div>
- </div>
-
- <!-- 提交按钮区域 -->
- <div class="submit-section">
- <t-button theme="primary" type="button" size="large"
- :loading="submitting" :disabled="!canSubmit || isSubmitDebounced"
- @click="handleSubmit">
- {{ props.isKbSettings ? '更新知识库设置' : (isUpdateMode ? '更新配置信息' : '完成配置') }}
- </t-button>
-
- <!-- 提交状态提示 -->
- <div v-if="!canSubmit && hasOllamaModels" class="submit-tips">
- <t-icon name="info-circle" class="tip-icon" />
- <span>请等待所有Ollama模型下载完成后再进行配置更新</span>
- </div>
-
- <!-- 远程API配置提示 -->
- <div v-if="!canSubmit && !hasOllamaModels" class="submit-tips">
- <t-icon name="info-circle" class="tip-icon" />
- <span>请完善模型配置信息</span>
- </div>
- </div>
- </t-form>
-
- <!-- Agent 帮助对话框 -->
- <t-dialog
- v-model:visible="showAgentHelp"
- header="Agent 智能问答模式说明"
- width="600px"
- :footer="false"
- >
- <div class="agent-help-content">
- <h4>什么是 Agent 模式?</h4>
- <p>Agent 模式基于 ReAct (Reasoning + Acting) 框架,能够通过以下方式回答复杂问题:</p>
- <ul>
- <li><strong>多步推理</strong>:Agent 会分步思考和分析问题</li>
- <li><strong>工具调用</strong>:根据需要调用知识库检索等工具</li>
- <li><strong>自我反思</strong>:评估中间结果并调整策略</li>
- <li><strong>上下文记忆</strong>:支持多轮连续对话</li>
- </ul>
-
- <h4>适用场景</h4>
- <ul>
- <li>需要对比分析多个文档</li>
- <li>需要多步推理的复杂问题</li>
- <li>需要在多个知识库中查找信息</li>
- <li>需要深度分析和总结</li>
- </ul>
-
- <h4>与普通模式的区别</h4>
- <table class="comparison-table">
- <tr>
- <th>特性</th>
- <th>普通模式</th>
- <th>Agent 模式</th>
- </tr>
- <tr>
- <td>推理方式</td>
- <td>单次检索+生成</td>
- <td>多步推理循环</td>
- </tr>
- <tr>
- <td>工具使用</td>
- <td>固定流程</td>
- <td>动态决策</td>
- </tr>
- <tr>
- <td>适用问题</td>
- <td>简单直接问题</td>
- <td>复杂推理问题</td>
- </tr>
- <tr>
- <td>响应时间</td>
- <td>快</td>
- <td>相对较慢</td>
- </tr>
- </table>
- </div>
- </t-dialog>
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-/**
- * 导入必要的 Vue 组合式 API 和外部依赖
- */
-import { ref, reactive, computed, watch, onMounted, onUnmounted, nextTick } from 'vue';
-import { useRouter, useRoute } from 'vue-router';
-import { MessagePlugin } from 'tdesign-vue-next';
-import { ChevronDownIcon } from 'tdesign-icons-vue-next';
-import {
- initializeSystemByKB,
- checkOllamaStatus,
- checkOllamaModels,
- downloadOllamaModel,
- getDownloadProgress,
- getCurrentConfigByKB,
- checkRemoteModel,
- type DownloadTask,
- checkRerankModel,
- testMultimodalFunction,
- listOllamaModels,
- testEmbeddingModel,
- extractTextRelations,
- fabriText,
- fabriTag,
- type TextRelationExtractionRequest,
- type Node,
- type Relation,
- type FabriTagRequest,
- type FabriTextRequest
-} 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;
-} | null;
-const form = ref<TFormRef>(null);
-const submitting = ref(false);
-const hasFiles = ref(false);
-const isUpdateMode = ref(false); // 是否为更新模式
-const tagOptionsDefault = [
- { label: '内容', value: '内容' },
- { label: '文化', value: '文化' },
- { label: '人物', value: '人物' },
- { label: '事件', value: '事件' },
- { label: '时间', value: '时间' },
- { label: '地点', value: '地点' },
- { label: '作品', value: '作品' },
- { label: '作者', value: '作者' },
- { label: '关系', value: '关系' },
- { label: '属性', value: '属性' }
-];
-const tagOptions = ref([] as {label: string, value: string}[]);
-const tagInput = ref('');
-const popupVisibleNode1 = ref<boolean[]>([]);
-const popupVisibleNode2 = ref<boolean[]>([]);
-const tagFabring = ref(false);
-const textFabring = ref(false);
-const extracting = 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({
- // 知识库基本信息 (仅在知识库设置模式下使用)
- kbName: '',
- kbDescription: '',
- llm: {
- source: 'local',
- modelName: '',
- baseUrl: '',
- apiKey: ''
- },
- embedding: {
- source: 'local',
- modelName: '',
- baseUrl: '',
- apiKey: '',
- dimension: 0 // 默认嵌入维度值
- },
- rerank: {
- enabled: false,
- modelName: '',
- baseUrl: '',
- apiKey: ''
- },
- multimodal: {
- enabled: false,
- storageType: 'minio' as 'minio' | 'cos',
- vlm: {
- modelName: '',
- baseUrl: '',
- apiKey: '',
- interfaceType: 'ollama'
- },
- cos: {
- secretId: '',
- secretKey: '',
- region: '',
- bucketName: '',
- appId: '',
- pathPrefix: ''
- },
- minio: {
- bucketName: '',
- useSSL: false,
- pathPrefix: ''
- }
- },
- documentSplitting: {
- chunkSize: 512,
- chunkOverlap: 100,
- separators: ['\n\n', '\n', '。', '!', '?', ';', ';']
- },
- nodeExtract: {
- enabled: false,
- text: '',
- tags: [] as string[],
- nodes: [] as Node[],
- relations: [] as Relation[]
- },
- agent: {
- enabled: false,
- maxIterations: 5,
- temperature: 0.7,
- thinkingModelId: '',
- allowedTools: ['knowledge_search', 'multi_kb_search', 'list_knowledge_bases']
- }
-});
-
-// Agent 帮助对话框状态
-const showAgentHelp = ref(false);
-
-// 输入防抖定时器
-const inputDebounceTimers = reactive<Record<string, any>>({});
-
-// Embedding 维度检测状态
-const embeddingDimDetecting = ref(false);
-
-// 预设配置选择
-const selectedPreset = ref('precision');
-
-// 分隔符选项
-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 multimodalTest = reactive({
- uploadedFiles: [],
- selectedFile: null as File | null,
- previewUrl: '',
- testing: false,
- result: null as any
-});
-
-// 计算属性
-const isVlmOllama = computed(() => {
- return formData.multimodal.vlm.interfaceType === 'ollama';
-});
-
-const hasOllamaModels = computed(() => {
- // 检查是否真正需要Ollama模型
- const needsLlmOllama = formData.llm.source === 'local' && formData.llm.modelName;
- const needsEmbeddingOllama = formData.embedding.source === 'local' && formData.embedding.modelName;
- const needsVlmOllama = formData.multimodal.enabled &&
- formData.multimodal.vlm.interfaceType === 'ollama' &&
- formData.multimodal.vlm.modelName;
-
- return needsLlmOllama || needsEmbeddingOllama || needsVlmOllama;
-});
-
-const canTestMultimodal = computed(() => {
- // 检查VLM模型配置是否完整
- const vlmConfigComplete = formData.multimodal.vlm.modelName &&
- (formData.multimodal.vlm.interfaceType === 'ollama' ||
- (formData.multimodal.vlm.interfaceType === 'openai' && formData.multimodal.vlm.baseUrl));
-
- // 检查存储配置是否完整
- let storageConfigComplete = false;
- if (formData.multimodal.storageType === 'cos') {
- storageConfigComplete = !!(formData.multimodal.cos.secretId &&
- formData.multimodal.cos.secretKey &&
- formData.multimodal.cos.region &&
- formData.multimodal.cos.bucketName &&
- formData.multimodal.cos.appId);
- } else if (formData.multimodal.storageType === 'minio') {
- storageConfigComplete = !!formData.multimodal.minio.bucketName;
- }
-
- return vlmConfigComplete && storageConfigComplete;
-});
-
-const canSubmit = computed(() => {
- // 基本必填项检查
- const basicRequired = formData.llm.modelName &&
- formData.embedding.modelName;
-
- if (!basicRequired) return false;
-
- // LLM模型检查
- let llmOk = true;
- if (formData.llm.source === 'local') {
- // Ollama模型需要检查可用性
- llmOk = modelStatus.llm.available && !modelStatus.llm.downloading;
- } else {
- // 远程API只需要有BaseURL即可(如果需要的话,在表单验证中处理)
- llmOk = true;
- }
-
- // Embedding模型检查
- let embeddingOk = true;
- if (formData.embedding.source === 'local') {
- // Ollama模型需要检查可用性
- embeddingOk = modelStatus.embedding.available && !modelStatus.embedding.downloading;
- } else {
- // 远程API只需要有BaseURL即可
- embeddingOk = true;
- }
-
- // Rerank模型检查(如果启用)
- let rerankOk = true;
- if (formData.rerank.enabled && formData.rerank.modelName) {
- if (formData.rerank.baseUrl) {
- // 远程API,不需要特殊检查
- rerankOk = true;
- } else {
- // 本地Ollama模型需要检查可用性
- rerankOk = modelStatus.rerank.available && !modelStatus.rerank.downloading;
- }
- }
-
- // VLM模型检查(如果启用多模态)
- let vlmOk = true;
- if (formData.multimodal.enabled && formData.multimodal.vlm.modelName) {
- if (formData.multimodal.vlm.interfaceType === 'ollama') {
- // Ollama模型需要检查可用性
- vlmOk = modelStatus.vlm.available && !modelStatus.vlm.downloading;
- } else {
- // OpenAI兼容API,不需要特殊检查
- vlmOk = true;
- }
- }
-
- let extractOk = true;
- if (formData.nodeExtract.enabled) {
- if (formData.nodeExtract.text === '') {
- extractOk = false;
- }
- for (let i = 0; i < formData.nodeExtract.tags.length; i++) {
- const tag = formData.nodeExtract.tags[i];
- if (tag == '') {
- extractOk = false;
- break;
- }
- }
-
- if (!readyNode.value){
- extractOk = false;
- }
- if (!readyRelation.value){
- extractOk = false;
- }
- }
-
- return llmOk && embeddingOk && rerankOk && vlmOk && extractOk;
-});
-
-const imageUpload = ref(null);
-
-// 清理完成,开始函数定义
-
-// 验证Embedding维度
-const validateEmbeddingDimension = (val: any) => {
- val = Number(val);
- if (!val || isNaN(val)) {
- return false;
- }
- // 验证是否为整数且在合理范围内
- return Number.isInteger(val) ;
-};
-
-// 表单验证规则
-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' }
- ],
- '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' }
- ],
- 'nodeExtract.text': [
- { required: true, message: '请输入文本内容', type: 'error' },
- { min: 10, message: '文本内容至少需要10个字符', 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);
- }
-
- // 添加VLM模型检查
- 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;
- }
-
- // 更新VLM模型状态
- 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) {
- console.log(`模型 ${modelName} 正在下载中,忽略重复点击`);
- return;
- }
-
- console.log(`开始下载模型: ${type} - ${modelName}`);
-
- 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 loadCurrentConfig = async () => {
- try {
- // 如果是知识库设置模式,先加载知识库基本信息
- 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
- if (props.isKbSettings && !currentKbId.value) {
- console.error('知识库设置模式下缺少知识库ID');
- return;
- }
- const config = await getCurrentConfigByKB(currentKbId.value!);
-
- // 设置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);
- console.log('LLM config loaded:', formData.llm);
- }
- if (config.embedding) {
- Object.assign(formData.embedding, config.embedding);
- console.log('Embedding config loaded:', formData.embedding);
- }
- if (config.rerank) {
- Object.assign(formData.rerank, config.rerank);
- console.log('Rerank config loaded:', formData.rerank);
- }
- if (config.multimodal) {
- Object.assign(formData.multimodal, config.multimodal);
- // 强制同步 storageType 到单选框
- await nextTick();
- formData.multimodal.storageType = (config.multimodal.storageType || 'minio') as 'minio' | 'cos';
- console.log('Multimodal config loaded:', formData.multimodal);
- }
- 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';
- }
- } else {
- // 如果没有文档分割配置,确保使用默认的precision模式
- selectedPreset.value = 'precision';
- }
- if (config.nodeExtract.enabled) {
- formData.nodeExtract.enabled = true;
- formData.nodeExtract.text = config.nodeExtract.text;
- formData.nodeExtract.tags = config.nodeExtract.tags;
- formData.nodeExtract.nodes = config.nodeExtract.nodes;
- formData.nodeExtract.relations = config.nodeExtract.relations;
- tagOptions.value = [];
- for (const tag of config.nodeExtract.tags) {
- if (tagOptions.value.find((item) => item.value === tag)) {
- continue;
- }
- tagOptions.value.push({ label: tag, value: tag });
- }
- }
-
- // 回填 Agent 配置
- if ((config as any).agent) {
- Object.assign(formData.agent, {
- enabled: (config as any).agent.enabled || false,
- maxIterations: (config as any).agent.maxIterations || 5,
- temperature: (config as any).agent.temperature || 0.7,
- thinkingModelId: (config as any).agent.thinkingModelId || '',
- allowedTools: (config as any).agent.allowedTools || ['knowledge_search', 'multi_kb_search', 'list_knowledge_bases']
- });
- console.log('Agent config loaded:', formData.agent);
- }
-
- // 在配置加载完成后,检查模型状态
- await checkModelsAfterLoading(config);
-
- } catch (error) {
- console.warn('Failed to load current configuration:', error);
- // 如果加载失败,使用默认配置
- isUpdateMode.value = false;
- }
-};
-
-// 加载配置后检查模型状态
-const checkModelsAfterLoading = async (config: any) => {
- // 延迟一点执行,确保DOM已经更新
- setTimeout(async () => {
- // 检查所有已配置模型的状态
- await checkAllConfiguredModels();
-
- // 检查Rerank模型状态
- if (formData.rerank.enabled && formData.rerank.modelName && formData.rerank.baseUrl) {
- await checkRerankModelStatus();
- }
- }, 300);
-};
-
-// 事件处理
-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;
- // 不清除 downloading 状态,避免中断正在进行的下载
-
- 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;
- // 不清除 downloading 状态,避免中断正在进行的下载
-
- 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 = '';
- // 不清除 downloading 状态,避免中断正在进行的下载
- } else {
- modelStatus[type].checked = false;
- modelStatus[type].available = false;
- modelStatus[type].message = '';
- // 不清除 downloading 状态,避免中断正在进行的下载
- }
-
- // 设置防抖延迟
- 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 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 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();
- }
- }
-
- // 检查VLM模型
- if (formData.multimodal.enabled && formData.multimodal.vlm.modelName) {
- if (isVlmOllama.value && ollamaStatus.available) {
- await checkAllOllamaModels();
- }
- // VLM远程API校验可以在这里添加
- }
-};
-
-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;
- }
-};
-
-// 第一个handleSubmit函数已删除,使用下面完整的版本
-
-// 停止所有进度轮询
-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;
- }
-});
-
-// 监听表单变化
-watch(() => formData.llm.source, () => onModelSourceChange('llm'));
-watch(() => formData.embedding.source, () => onModelSourceChange('embedding'));
-
-// 监听路由参数变化,当知识库ID变化时重新加载配置
-watch(() => route.params.kbId, async (newKbId, oldKbId) => {
- // 只有在知识库设置模式下且ID确实发生变化时才重新加载
- if (props.isKbSettings && newKbId && newKbId !== oldKbId) {
- console.log('知识库ID变化,重新加载配置:', { oldKbId, newKbId });
- await loadCurrentConfig();
- await checkAllConfiguredModels();
- }
-}, { immediate: false });
-
-// 添加缺失的函数
-const onRerankChange = () => {
- console.log('Rerank enabled:', formData.rerank.enabled);
-};
-
-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';
- }
-
- // 如果选择了Ollama接口,检查Ollama状态
- if (formData.multimodal.vlm.interfaceType === 'ollama' && !ollamaStatus.checked) {
- await checkOllama();
- }
- } else {
- // 如果禁用多模态,重置VLM模型状态
- modelStatus.vlm.checked = false;
- modelStatus.vlm.available = false;
- modelStatus.vlm.downloading = false;
- modelStatus.vlm.message = '';
- }
-};
-
-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 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 onVlmInterfaceTypeChange = async () => {
- console.log('VLM interface type changed:', formData.multimodal.vlm.interfaceType);
-
- // 重置VLM模型状态
- modelStatus.vlm.checked = false;
- modelStatus.vlm.available = false;
- modelStatus.vlm.downloading = false;
- modelStatus.vlm.message = '';
-
- // 如果切换到Ollama接口,检查Ollama状态
- if (formData.multimodal.vlm.interfaceType === 'ollama') {
- if (!ollamaStatus.checked) {
- await checkOllama();
- }
-
- // 如果已经有模型名称,立即检查模型状态
- if (formData.multimodal.vlm.modelName && ollamaStatus.available) {
- await checkAllOllamaModels();
- }
- }
-};
-
-const onVlmBaseUrlChange = async () => {
- console.log('VLM base URL changed:', formData.multimodal.vlm.baseUrl);
-};
-
-const onVlmBaseUrlInput = () => {
- console.log('VLM base URL input');
-};
-
-const onVlmApiKeyChange = () => {
- console.log('VLM API key changed');
-};
-
-const onCosConfigChange = () => {
- console.log('COS config changed');
-};
-
-const onStorageTypeChange = () => {
- console.log('Storage type changed:', formData.multimodal.storageType);
-};
-
-const onImageChange = (files: any) => {
- if (files && files.length > 0) {
- // 检查多模态配置是否完整
- const missingConfigs: string[] = [];
-
- // 根据存储类型检查必填项
- if (formData.multimodal.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.multimodal.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.multimodal.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.multimodal.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 handleSubmit = async () => {
- // 防止重复提交和防抖
- if (submitting.value || isSubmitDebounced.value) {
- return;
- }
-
- // 启动防抖机制
- isSubmitDebounced.value = true;
- if (submitDebounceTimer.value) {
- clearTimeout(submitDebounceTimer.value);
- }
- submitDebounceTimer.value = setTimeout(() => {
- isSubmitDebounced.value = false;
- }, 3000); // 3秒防抖
-
- try {
- // 表单验证
- const isValid = await form.value?.validate();
- if (!isValid) {
- MessagePlugin.error('请检查表单填写是否正确');
- return;
- }
-
- 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);
- }
-
- // 根据是否为知识库设置模式选择不同的API
- if (props.isKbSettings && !currentKbId.value) {
- console.error('知识库设置模式下缺少知识库ID');
- MessagePlugin.error('知识库ID缺失,无法保存配置');
- return;
- }
- const result = await initializeSystemByKB(currentKbId.value!, formData);
-
- if (result.success) {
- MessagePlugin.success(props.isKbSettings ? '知识库设置更新成功' : (isUpdateMode.value ? '配置更新成功' : '系统初始化完成'));
-
- // 根据不同模式进行跳转
- if (props.isKbSettings && currentKbId.value) {
- // 知识库设置模式,跳转回知识库详情页面
- setTimeout(() => {
- router.push(`/platform/knowledge-bases/${currentKbId.value}`);
- }, 1500);
- } else if (!isUpdateMode.value) {
- // 初始化模式,跳转到知识库列表页面
- setTimeout(() => {
- router.push('/platform/knowledge-bases');
- }, 1500);
- }
- } else {
- MessagePlugin.error(result.message || '操作失败');
- }
- } catch (error: any) {
- console.error('提交失败:', error);
- MessagePlugin.error(error.message || '操作失败,请检查网络连接');
- } finally {
- submitting.value = false;
-
- // 清理防抖定时器
- if (submitDebounceTimer.value) {
- clearTimeout(submitDebounceTimer.value);
- submitDebounceTimer.value = null;
- }
- isSubmitDebounced.value = false;
- }
-};
-
-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 addTag = async (val: string) => {
- val = val.trim();
- if (val === '') {
- MessagePlugin.error('请输入有效的标签');
- return;
- }
- if (!tagOptions.value.find(item => item.value === val)){
- tagOptions.value.push({ label: val, value: val });
- }
- if (!formData.nodeExtract.tags.includes(val)) {
- formData.nodeExtract.tags.push(val);
- }else {
- MessagePlugin.error('该标签已存在');
- }
- tagInput.value = '';
-}
-
-const clearTags = async () => {
- formData.nodeExtract.tags = [];
-}
-
-const defaultExtractExample = async () => {
- formData.nodeExtract.tags = ['作者', '别名'];
- formData.nodeExtract.text = `《红楼梦》,又名《石头记》,是清代作家曹雪芹创作的中国古典四大名著之一,被誉为中国封建社会的百科全书。该书前80回由曹雪芹所著,后40回一般认为是高鹗所续。小说以贾、史、王、薛四大家族的兴衰为背景,以贾宝玉、林黛玉和薛宝钗的爱情悲剧为主线,刻画了以贾宝玉和金陵十二钗为中心的正邪两赋、贤愚并出的高度复杂的人物群像。成书于乾隆年间(1743年前后),是中国文学史上现实主义的高峰,对后世影响深远。`;
- formData.nodeExtract.nodes = [
- {name: '红楼梦', attributes: ['中国古典四大名著之一', '又名《石头记》', '被誉为中国封建社会的百科全书']},
- {name: '石头记', attributes: ['《红楼梦》的别名']},
- {name: '曹雪芹', attributes: ['清代作家', '《红楼梦》前 80 回的作者']},
- {name: '高鹗', attributes: ['一般认为是《红楼梦》后 40 回的续写者']}
- ];
- formData.nodeExtract.relations = [
- {node1: '红楼梦', node2: '石头记', type: '别名'},
- {node1: '红楼梦', node2: '曹雪芹', type: '作者'},
- {node1: '红楼梦', node2: '高鹗', type: '作者'}
- ];
- tagOptions.value = [];
- tagOptions.value.push({ label: '作者', value: '作者' });
- tagOptions.value.push({ label: '别名', value: '别名' });
- popupVisibleNode1.value = Array(formData.nodeExtract.nodes.length).fill(false);
- popupVisibleNode2.value = Array(formData.nodeExtract.nodes.length).fill(false);
-}
-
-const clearExtractExample = async () => {
- formData.nodeExtract.tags = [];
- formData.nodeExtract.text = '';
- formData.nodeExtract.nodes = [];
- formData.nodeExtract.relations = [];
- tagOptions.value = [...tagOptionsDefault];
- popupVisibleNode1.value = [];
- popupVisibleNode2.value = [];
-}
-
-const addNode = async () =>{
- formData.nodeExtract.nodes.push({
- name: '',
- attributes: []
- });
-}
-
-const removeNode = async (index: number) => {
- formData.nodeExtract.nodes.splice(index, 1);
-}
-
-const addAttribute = async (nodeIndex: number) => {
- formData.nodeExtract.nodes[nodeIndex].attributes.push('');
-}
-
-const removeAttribute = async(nodeIndex: number, attrIndex: number) => {
- formData.nodeExtract.nodes[nodeIndex].attributes.splice(attrIndex, 1);
-}
-
-const onRelationNode1OptionClick = async (index: number, item: Node) => {
- formData.nodeExtract.relations[index].node1 = item.name;
- popupVisibleNode1.value[index] = false;
-}
-
-const onRelationNode2OptionClick = async (index: number, item: Node) => {
- formData.nodeExtract.relations[index].node2 = item.name;
- popupVisibleNode2.value[index] = false;
-}
-
-const relationOnClearNode1 = async (index: number) => {
- formData.nodeExtract.relations[index].node1 = '';
-}
-
-const relationOnClearNode2 = async (index: number) => {
- formData.nodeExtract.relations[index].node2 = '';
-}
-
-const onPopupVisibleNode1Change = async (index: number, val: boolean) => {
- popupVisibleNode1.value[index] = val;
-};
-
-const onPopupVisibleNode2Change = async (index: number, val: boolean) => {
- popupVisibleNode2.value[index] = val;
-};
-
-const addRelation = async () => {
- formData.nodeExtract.relations.push({
- node1: '',
- node2: '',
- type: ''
- });
- popupVisibleNode1.value.push(false);
- popupVisibleNode2.value.push(false);
-}
-
-const removeRelation = async (index: number) => {
- formData.nodeExtract.relations.splice(index, 1);
-}
-
-const onFocus = async () => {};
-
-const canExtract = async (): Promise<boolean> =>{
- if (formData.nodeExtract.text === '') {
- MessagePlugin.error('请输入示例文本');
- return false;
- }
- if (formData.nodeExtract.tags.length === 0) {
- MessagePlugin.error('请输入关系类型');
- return false;
- }
- for (let i = 0; i < formData.nodeExtract.tags.length; i++) {
- if (formData.nodeExtract.tags[i] === '') {
- MessagePlugin.error('请输入关系类型');
- return false;
- }
- }
- if (!modelStatus.llm.available) {
- MessagePlugin.error('请输入 LLM 大语言模型配置');
- return false;
- }
- return true;
-}
-
-const readyNode = computed(() => {
- for (let i = 0; i < formData.nodeExtract.nodes.length; i++) {
- let node = formData.nodeExtract.nodes[i];
- if (node.name === '') {
- return false;
- }
- if (node.attributes){
- for (let j = 0; j < node.attributes.length; j++) {
- if (node.attributes[j] === '') {
- return false;
- }
- }
- }
- }
- return formData.nodeExtract.nodes.length > 0;
-})
-
-const readyRelation = computed(() => {
- for (let i = 0; i < formData.nodeExtract.relations.length; i++) {
- let relation = formData.nodeExtract.relations[i];
- if (relation.node1 == '' || relation.node2 == '' || relation.type == '' ) {
- return false
- }
- }
- return formData.nodeExtract.relations.length > 0;
-})
-
-// 处理提取
-const handleExtract = async () => {
- if (extracting.value) return;
-
- try {
- // 表单验证
- const isValid = await form.value?.validate();
- if (!isValid) {
- MessagePlugin.error('请检查表单填写是否正确');
- return;
- }
- if (!canExtract()){
- return;
- }
-
- extracting.value = true;
-
- const request: TextRelationExtractionRequest = {
- text: formData.nodeExtract.text.trim(),
- tags: formData.nodeExtract.tags,
- llmConfig: {
- source: formData.llm.source as 'local' | 'remote',
- modelName: formData.llm.modelName,
- baseUrl: formData.llm.baseUrl,
- apiKey: formData.llm.apiKey,
- },
- };
-
- const result = await extractTextRelations(request);
- if (result.nodes.length === 0 ) {
- MessagePlugin.info('未提取有效节点');
- } else {
- formData.nodeExtract.nodes = result.nodes;
- }
- if ( result.relations.length === 0) {
- MessagePlugin.info('未提取有效关系');
- } else {
- formData.nodeExtract.relations = result.relations;
- }
- } catch (error) {
- console.error('文本内容关系提取失败:', error);
- MessagePlugin.error('提取失败,请检查网络连接或文本内容格式');
- } finally {
- extracting.value = false;
- }
-};
-
-// 处理标签
-const handleFabriTag = async () => {
- if (tagFabring.value) return;
-
- try {
- // 表单验证
- const isValid = await form.value?.validate();
- if (!isValid) {
- MessagePlugin.error('请检查表单填写是否正确');
- return;
- }
-
- tagFabring.value = true;
-
- const request: FabriTagRequest = {
- llmConfig: {
- source: formData.llm.source as 'local' | 'remote',
- modelName: formData.llm.modelName,
- baseUrl: formData.llm.baseUrl,
- apiKey: formData.llm.apiKey,
- },
- };
-
- const result = await fabriTag(request);
- formData.nodeExtract.tags = result.tags;
- tagOptions.value = [];
- for (let i = 0; i < result.tags.length; i++) {
- tagOptions.value.push({ label: result.tags[i], value: result.tags[i] });
- }
-
- } catch (error) {
- console.error('随机生成标签:', error);
- MessagePlugin.error('生成失败,请重试');
- } finally {
- tagFabring.value = false;
- }
-};
-
-// 处理示例文本
-const handleFabriText = async () => {
- if (textFabring.value) return;
-
- try {
- // 表单验证
- const isValid = await form.value?.validate();
- if (!isValid) {
- MessagePlugin.error('请检查表单填写是否正确');
- return;
- }
-
- textFabring.value = true;
-
- const request: FabriTextRequest = {
- tags: formData.nodeExtract.tags,
- llmConfig: {
- source: formData.llm.source as 'local' | 'remote',
- modelName: formData.llm.modelName,
- baseUrl: formData.llm.baseUrl,
- apiKey: formData.llm.apiKey,
- },
- };
-
- const result = await fabriText(request);
- formData.nodeExtract.text = result.text;
- } catch (error) {
- console.error('生成示例文本失败:', error);
- MessagePlugin.error('生成失败,请重试');
- } finally {
- textFabring.value = false;
- }
-};
-
-
-// 组件挂载时检查Ollama状态
-onMounted(async () => {
- // 加载当前配置
- await loadCurrentConfig();
-
- // 总是检查Ollama状态,因为这是独立于具体配置的
- await refreshOllamaSummary();
-
- // 检查已配置模型状态
- await checkAllConfiguredModels();
-});
-</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 {
- margin-bottom: 24px;
- background: #ffffff;
- border: 1px solid #e9edf5;
- border-radius: 12px;
- box-shadow: 0 8px 24px rgba(15, 23, 42, 0.05);
- padding: 16px 20px;
-
- .summary-header {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-bottom: 12px;
-
- .title {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- font-weight: 600;
- color: #1f2937;
- font-size: 16px;
- }
- .state{ margin-left: 8px; }
- .refresh-icon{
- margin-left: 8px;
- 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: 12px;
- margin-bottom: 12px;
-
- &:last-child {
- margin-bottom: 0;
- }
-
- .label {
- color: #6b7280;
- font-size: 14px;
- margin-top: 2px;
- min-width: 100px;
- }
- .model-list {
- display: flex;
- gap: 8px;
- flex-wrap: wrap;
- }
- .model-pill {
- border-radius: 8px;
- }
- .empty {
- color: #9ca3af;
- font-size: 14px;
- }
- }
- }
- }
-
- .config-section {
- margin-bottom: 32px;
- background: #fff;
- border: 1px solid #eef4f0;
- border-radius: 12px;
- box-shadow: 0 6px 18px rgba(7, 192, 95, 0.04);
- padding: 24px;
-
- h3 {
- display: flex;
- align-items: center;
- gap: 8px;
- margin: 0 0 20px;
- font-size: 18px;
- font-weight: 600;
- color: #0f172a;
-
- .section-icon {
- color: #07c05f;
- font-size: 20px;
- }
- }
-
- .add-tag-container {
- display: flex;
- align-items: center; /* 垂直居中 */
- justify-content: flex-start; /* 水平起始对齐 */
- gap: 8px;
- }
- .extract-button {
- display: flex;
- justify-content: center;
- align-items: center;
- gap: 12px;
- text-align: center;
- }
-
- .node-list {
- display: flex;
- flex-wrap: wrap;
- gap: 12px;
- }
-
- .node-header {
- display: flex;
- align-items: center;
- justify-content: flex-start;
- gap: 4px;
- margin-bottom: 8px;
- }
-
- .attribute-item {
- display: flex;
- align-items: center;
- justify-content: flex-start;
- margin-bottom: 4px;
- }
-
- .relation-line {
- display: flex;
- align-items: center;
- justify-content: flex-start;
- gap: 4px;
- }
-
- .relation-arrow {
- font-size: 50px;
- }
-
- .sample-text-form {
- display: flex;
- flex-direction: column;
- width: 100%;
- }
- }
-
- .btn-tips-form {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-bottom: 12px;
-
- .btn-tips {
- display: flex;
- align-items: center;
- justify-content: center;
- color: #fa8c16;
-
- .tip-icon {
- margin-right: 6px;
- }
- }
- }
-
- .form-row {
- margin-bottom: 20px;
- }
-
- .model-input-with-status {
- display: flex;
- gap: 8px;
- align-items: center;
- }
-
- .model-input-with-status :deep(.t-input) {
- flex: 1;
- min-width: 300px;
- }
-
- .model-status-icon {
- flex-shrink: 0;
- min-width: 24px;
- display: flex;
- align-items: center;
- justify-content: center;
- }
-
- .model-status-icon .status-icon {
- font-size: 16px;
- cursor: help;
- padding: 4px;
- border-radius: 50%;
- transition: all 0.2s ease;
- }
-
- .model-status-icon .status-icon.installed {
- color: #16a34a;
- background: #f0fdf4;
- border: 1px solid #bbf7d0;
- }
-
- .model-status-icon .status-icon.not-installed {
- color: #dc2626;
- background: #fef2f2;
- border: 1px solid #fecaca;
- }
-
- .model-status-icon .status-icon.unknown {
- color: #d97706;
- background: #fffbeb;
- border: 1px solid #fed7aa;
- }
-
- .model-status-icon .status-icon.downloading {
- color: #16a34a;
- background: #f0fdf4;
- border: 1px solid #bbf7d0;
- animation: pulse 2s infinite;
- }
-
- .download-action {
- flex-shrink: 0;
- }
-
- .download-action .download-btn {
- height: 24px;
- width: 24px;
- min-width: 24px;
- padding: 0;
- border-radius: 4px;
- display: flex;
- align-items: center;
- justify-content: center;
- background: #16a34a;
- border: 1px solid #15803d;
- color: white;
- transition: all 0.2s ease;
- box-shadow: 0 1px 3px rgba(22, 163, 74, 0.2);
-
- &:hover:not(:disabled) {
- background: #15803d;
- border-color: #166534;
- box-shadow: 0 2px 6px rgba(22, 163, 74, 0.3);
- transform: translateY(-1px);
- }
-
- &:disabled {
- background: #e5e7eb;
- color: #9ca3af;
- cursor: not-allowed;
- box-shadow: none;
- }
-
- .t-icon {
- font-size: 14px;
- }
- }
-
- .model-download-status {
- display: inline-flex;
- align-items: center;
- gap: 6px;
-
- .download-progress-circle {
- flex-shrink: 0;
- }
-
- .download-percentage {
- font-size: 11px;
- font-weight: 600;
- color: #15803d;
- font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', monospace;
- white-space: nowrap;
- }
- }
-
- .remote-config {
- margin-top: 20px;
- // padding: 20px;
- // background: #f9fcff;
- // border-radius: 12px;
- // border: 1px solid #edf2f7;
- }
-
- .url-input-with-check {
- display: flex;
- align-items: center;
- gap: 8px;
- width: 100%;
- }
-
- .url-input-with-check :deep(.t-input) {
- flex: 1;
- min-width: 0;
- width: 100%;
- }
-
- .check-action {
- flex-shrink: 0;
- display: flex;
- align-items: center;
- justify-content: center;
- min-width: 24px;
- }
-
- .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.checking,
- .check-action .input-icon.checking {
- color: #0052d9;
- }
-
- .error-message {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-top: 12px;
- padding: 12px 16px;
- background-color: #fff2f0;
- border: 1px solid #ffccc7;
- border-radius: 8px;
- color: #d4380d;
- font-size: 14px;
-
- .t-icon {
- color: #d4380d;
- font-size: 16px;
- flex-shrink: 0;
- }
-
- span {
- line-height: 1.4;
- }
- }
-
- .dimension-input-with-action {
- display: flex;
- align-items: center;
- gap: 12px;
- }
- .dimension-input-with-action :deep(.t-input) {
- flex: 0 0 auto;
- }
- .detect-dim-btn {
- flex: 0 0 auto;
- }
-
- .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;
- }
- }
- }
-
- .rerank-config, .multimodal-config, .node-config {
- // margin-top: 20px;
- // padding: 20px;
- // background: #f9fcff;
- // border-radius: 12px;
- // border: 1px solid #edf2f7;
-
- h4 {
- color: #333;
- font-size: 16px;
- font-weight: 500;
- margin: 20px 0 15px 0;
- padding-left: 12px;
- border-left: 3px solid #07c05f;
- }
- }
-
- .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;
- }
- }
-
- .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;
- }
- }
- }
- }
-
- .submit-section {
- text-align: center;
- padding: 32px 0 0;
- // border-top: 1px solid #f0f0f0;
- // margin-top: 32px;
-
- :deep(.t-button--theme-primary) {
- background: linear-gradient(135deg, #07c05f, #00a651);
- border: none;
- border-radius: 8px;
- font-weight: 600;
- padding: 12px 32px;
- font-size: 16px;
- transition: all 0.2s ease;
- min-height: 44px;
- 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);
- }
-
- &.t-is-disabled {
- background: #ccc;
- color: #999;
- box-shadow: none;
- }
-
- &.t-is-loading {
- background: linear-gradient(135deg, #07c05f, #00a651);
- color: white;
- box-shadow: 0 4px 15px rgba(7, 192, 95, 0.2);
- }
- }
-
- .submit-tips {
- margin-top: 16px;
- display: flex;
- align-items: center;
- justify-content: center;
- color: #fa8c16;
- font-size: 14px;
-
- .tip-icon {
- margin-right: 6px;
- }
- }
- }
-
- // 动画定义
- @keyframes spin {
- from {
- transform: rotate(0deg);
- }
- to {
- transform: rotate(360deg);
- }
- }
-
- @keyframes pulse {
- 0%, 100% {
- opacity: 1;
- transform: scale(1);
- }
- 50% {
- opacity: 0.8;
- transform: scale(1.05);
- }
- }
-
- // 表单样式优化
- :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-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;
- }
- }
- }
-}
-
-.select-input-node {
- display: flex;
- flex-direction: column;
- padding: 0;
- gap: 2px;
-}
-
-.select-input-node > li {
- display: block;
- border-radius: 3px;
- line-height: 22px;
- cursor: pointer;
- padding: 3px 8px;
- color: var(--td-text-color-primary);
- transition: background-color 0.2s linear;
- white-space: nowrap;
- word-wrap: normal;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.select-input-node > li:hover {
- background-color: var(--td-bg-color-container-hover);
-}
-
-/* Agent 配置样式 */
-.agent-detail-config {
- margin-top: 16px;
- padding-left: 20px;
- border-left: 3px solid #0052d9;
-}
-
-.checkbox-with-label {
- display: flex;
- align-items: center;
-}
-
-.field-description {
- font-size: 12px;
- color: #00000099;
- margin-top: 4px;
-}
-
-/* Agent 帮助对话框样式 */
-.agent-help-content {
- h4 {
- font-size: 14px;
- font-weight: 600;
- color: #000000;
- margin: 16px 0 8px 0;
-
- &:first-child {
- margin-top: 0;
- }
- }
-
- p {
- font-size: 14px;
- color: #00000099;
- line-height: 1.6;
- margin: 8px 0;
- }
-
- ul {
- margin: 8px 0;
- padding-left: 20px;
-
- li {
- font-size: 14px;
- color: #00000099;
- line-height: 1.8;
-
- strong {
- color: #000000;
- }
- }
- }
-
- .comparison-table {
- width: 100%;
- border-collapse: collapse;
- margin: 12px 0;
- font-size: 13px;
-
- th, td {
- border: 1px solid #e7e7e7;
- padding: 8px 12px;
- text-align: left;
- }
-
- th {
- background: #f5f5f5;
- font-weight: 600;
- color: #000000;
- }
-
- td {
- color: #00000099;
- }
- }
-}
-</style>
\ No newline at end of file
diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue
index f6fa6b501..9fb362a3d 100644
--- a/frontend/src/views/knowledge/KnowledgeBase.vue
+++ b/frontend/src/views/knowledge/KnowledgeBase.vue
@@ -17,7 +17,9 @@ import {
listKnowledgeFiles,
} from "@/api/knowledge-base/index";
import { formatStringDate } from "@/utils/index";
+import { useI18n } from 'vue-i18n';
const route = useRoute();
+const { t } = useI18n();
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);
@@ -52,7 +54,7 @@ const loadKnowledgeFiles = async (kbIdValue: string) => {
}
const cardList_ = data.map((item: any) => {
- const rawName = item.file_name || item.title || item.source || '未命名文档'
+ const rawName = item.file_name || item.title || item.source || t('knowledgeBase.untitledDocument')
const dotIndex = rawName.lastIndexOf('.')
const displayName = dotIndex > 0 ? rawName.substring(0, dotIndex) : rawName
const fileTypeSource = item.file_type || (item.type === 'manual' ? 'MANUAL' : '')
@@ -224,7 +226,7 @@ const handleKBEditorSuccess = (kbIdValue: string) => {
const getTitle = (session_id: string, value: string) => {
const now = new Date().toISOString();
let obj = {
- title: '新会话',
+ title: t('knowledgeBase.newSession'),
path: `chat/${session_id}`,
id: session_id,
isMore: false,
@@ -245,10 +247,10 @@ async function createNewSession(value: string): Promise<void> {
getTitle(res.data.id, value);
} else {
// 错误处理
- console.error("创建会话失败");
+ console.error(t('knowledgeBase.createSessionFailed'));
}
}).catch(error => {
- console.error("创建会话出错:", error);
+ console.error(t('knowledgeBase.createSessionError'), error);
});
}
</script>
@@ -274,14 +276,14 @@ async function createNewSession(value: string): Promise<void> {
@click.stop="handleManualEdit(index, item)"
>
<t-icon class="icon" name="edit" />
- <span>编辑文档</span>
+ <span>{{ t('knowledgeBase.editDocument') }}</span>
</div>
<div
class="card-menu-item danger"
@click.stop="delCard(index, item)"
>
<t-icon class="icon" name="delete" />
- <span>删除文档</span>
+ <span>{{ t('knowledgeBase.deleteDocument') }}</span>
</div>
</div>
</template>
@@ -292,18 +294,18 @@ async function createNewSession(value: string): Promise<void> {
class="card-analyze"
>
<t-icon name="loading" class="card-analyze-loading"></t-icon>
- <span class="card-analyze-txt">解析中...</span>
+ <span class="card-analyze-txt">{{ t('knowledgeBase.parsingInProgress') }}</span>
</div>
<div
v-else-if="item.parse_status === 'failed'"
class="card-analyze failure"
>
<t-icon name="close-circle" class="card-analyze-loading failure"></t-icon>
- <span class="card-analyze-txt failure">解析失败</span>
+ <span class="card-analyze-txt failure">{{ t('knowledgeBase.parsingFailed') }}</span>
</div>
<div v-else-if="item.parse_status === 'draft'" class="card-draft">
- <t-tag size="small" theme="warning" variant="light-outline">草稿</t-tag>
- <span class="card-draft-tip">暂存内容,未参与检索</span>
+ <t-tag size="small" theme="warning" variant="light-outline">{{ t('knowledgeBase.draft') }}</t-tag>
+ <span class="card-draft-tip">{{ t('knowledgeBase.draftTip') }}</span>
</div>
<div v-else-if="item.parse_status === 'completed'" class="card-content-txt">
{{ item.description }}
@@ -321,14 +323,14 @@ async function createNewSession(value: string): Promise<void> {
<div class="circle-wrap">
<div class="header">
<img class="circle-img" src="@/assets/img/circle.png" alt="">
- <span class="circle-title">删除确认</span>
+ <span class="circle-title">{{ t('knowledgeBase.deleteConfirmation') }}</span>
</div>
<span class="del-circle-txt">
- {{ `确认要删除技能"${knowledge.file_name}",删除后不可恢复` }}
+ {{ t('knowledgeBase.confirmDeleteDocument', { fileName: knowledge.file_name || '' }) }}
</span>
<div class="circle-btn">
- <span class="circle-btn-txt" @click="delDialog = false">取消</span>
- <span class="circle-btn-txt confirm" @click="delCardConfirm">确认删除</span>
+ <span class="circle-btn-txt" @click="delDialog = false">{{ t('common.cancel') }}</span>
+ <span class="circle-btn-txt confirm" @click="delCardConfirm">{{ t('knowledgeBase.confirmDelete') }}</span>
</div>
</div>
</t-dialog>
diff --git a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue
index de9aa3baf..9a7a1bc4b 100644
--- a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue
+++ b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue
@@ -4,7 +4,7 @@
<div v-if="visible" class="settings-overlay" @click.self="handleClose">
<div class="settings-modal">
<!-- 关闭按钮 -->
- <button class="close-btn" @click="handleClose" aria-label="关闭">
+ <button class="close-btn" @click="handleClose" :aria-label="$t('general.close')">
<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
<path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>
@@ -14,7 +14,7 @@
<!-- 左侧导航 -->
<div class="settings-sidebar">
<div class="sidebar-header">
- <h2 class="sidebar-title">{{ mode === 'create' ? '新建知识库' : '知识库设置' }}</h2>
+ <h2 class="sidebar-title">{{ mode === 'create' ? $t('knowledgeEditor.titleCreate') : $t('knowledgeEditor.titleEdit') }}</h2>
</div>
<div class="settings-nav">
<div
@@ -36,23 +36,23 @@
<div v-show="currentSection === 'basic'" class="section">
<div v-if="formData" class="section-content">
<div class="section-header">
- <h3 class="section-title">基本信息</h3>
- <p class="section-desc">设置知识库的名称和描述信息</p>
+ <h3 class="section-title">{{ $t('knowledgeEditor.basic.title') }}</h3>
+ <p class="section-desc">{{ $t('knowledgeEditor.basic.description') }}</p>
</div>
<div class="section-body">
<div class="form-item">
- <label class="form-label required">知识库名称</label>
+ <label class="form-label required">{{ $t('knowledgeEditor.basic.nameLabel') }}</label>
<t-input
v-model="formData.name"
- placeholder="请输入知识库名称"
+ :placeholder="$t('knowledgeEditor.basic.namePlaceholder')"
:maxlength="50"
/>
</div>
<div class="form-item">
- <label class="form-label">知识库描述</label>
+ <label class="form-label">{{ $t('knowledgeEditor.basic.descriptionLabel') }}</label>
<t-textarea
v-model="formData.description"
- placeholder="请输入知识库描述(可选)"
+ :placeholder="$t('knowledgeEditor.basic.descriptionPlaceholder')"
:maxlength="200"
:autosize="{ minRows: 3, maxRows: 6 }"
/>
@@ -99,10 +99,10 @@
<!-- 保存按钮 -->
<div class="settings-footer">
<t-button theme="default" variant="outline" @click="handleClose">
- 取消
+ {{ $t('common.cancel') }}
</t-button>
<t-button theme="primary" @click="handleSubmit" :loading="saving">
- {{ mode === 'create' ? '创建知识库' : '保存配置' }}
+ {{ mode === 'create' ? $t('knowledgeEditor.buttons.create') : $t('knowledgeEditor.buttons.save') }}
</t-button>
</div>
</div>
@@ -123,8 +123,10 @@ import { useUIStore } from '@/stores/ui'
import KBModelConfig from './settings/KBModelConfig.vue'
import KBChunkingSettings from './settings/KBChunkingSettings.vue'
import KBAdvancedSettings from './settings/KBAdvancedSettings.vue'
+import { useI18n } from 'vue-i18n'
const uiStore = useUIStore()
+const { t } = useI18n()
// Props
const props = defineProps<{
@@ -145,12 +147,12 @@ const loading = ref(false)
const allModels = ref<any[]>([])
const hasFiles = ref(false)
-const navItems = [
- { key: 'basic', icon: 'info-circle', label: '基本信息' },
- { key: 'models', icon: 'control-platform', label: '模型配置' },
- { key: 'chunking', icon: 'file-copy', label: '分块设置' },
- { key: 'advanced', icon: 'setting', label: '高级设置' }
-]
+const navItems = computed(() => [
+ { key: 'basic', icon: 'info-circle', label: t('knowledgeEditor.sidebar.basic') },
+ { key: 'models', icon: 'control-platform', label: t('knowledgeEditor.sidebar.models') },
+ { key: 'chunking', icon: 'file-copy', label: t('knowledgeEditor.sidebar.chunking') },
+ { key: 'advanced', icon: 'setting', label: t('knowledgeEditor.sidebar.advanced') }
+])
// 模型配置引用
const modelConfigRef = ref<InstanceType<typeof KBModelConfig>>()
@@ -206,8 +208,8 @@ const loadAllModels = async () => {
const models = await listModels()
allModels.value = models || []
} catch (error) {
- console.error('加载模型列表失败:', error)
- MessagePlugin.error('加载模型列表失败')
+ console.error('Failed to load model list:', error)
+ MessagePlugin.error(t('knowledgeEditor.messages.loadModelsFailed'))
allModels.value = []
}
}
@@ -225,7 +227,7 @@ const loadKBData = async () => {
])
if (!kbInfo || !kbInfo.data) {
- throw new Error('知识库不存在')
+ throw new Error(t('knowledgeEditor.messages.notFound'))
}
const kb = kbInfo.data
@@ -270,8 +272,8 @@ const loadKBData = async () => {
}
}
} catch (error) {
- console.error('加载知识库数据失败:', error)
- MessagePlugin.error('加载知识库数据失败')
+ console.error('Failed to load knowledge base data:', error)
+ MessagePlugin.error(t('knowledgeEditor.messages.loadDataFailed'))
handleClose()
} finally {
loading.value = false
@@ -309,29 +311,29 @@ const validateForm = (): boolean => {
// 验证基本信息
if (!formData.value.name || !formData.value.name.trim()) {
- MessagePlugin.warning('请输入知识库名称')
+ MessagePlugin.warning(t('knowledgeEditor.messages.nameRequired'))
currentSection.value = 'basic'
return false
}
// 验证模型配置 - 必须配置 embedding 和 summary 模型
if (!formData.value.modelConfig.embeddingModelId) {
- MessagePlugin.warning('请选择 Embedding 模型')
+ MessagePlugin.warning(t('knowledgeEditor.messages.embeddingRequired'))
currentSection.value = 'models'
return false
}
if (!formData.value.modelConfig.llmModelId) {
- MessagePlugin.warning('请选择 Summary 模型')
+ MessagePlugin.warning(t('knowledgeEditor.messages.summaryRequired'))
currentSection.value = 'models'
return false
}
// 验证多模态配置(如果启用)
if (formData.value.multimodalConfig.enabled) {
- const validation = advancedSettingsRef.value?.validateMultimodal()
+ const validation = (advancedSettingsRef.value as any)?.validateMultimodal?.()
if (validation && !validation.valid) {
- MessagePlugin.warning(validation.message || '多模态配置验证失败')
+ MessagePlugin.warning(validation.message || t('knowledgeEditor.messages.multimodalInvalid'))
currentSection.value = 'advanced'
return false
}
@@ -411,21 +413,21 @@ const handleSubmit = async () => {
try {
const data = buildSubmitData()
if (!data) {
- throw new Error('数据构建失败')
+ throw new Error(t('knowledgeEditor.messages.buildDataFailed'))
}
if (props.mode === 'create') {
// 创建模式:一次性创建知识库及所有配置
- const result = await createKnowledgeBase(data)
+ const result: any = await createKnowledgeBase(data)
if (!result.success || !result.data?.id) {
- throw new Error(result.message || '创建知识库失败')
+ throw new Error(result.message || t('knowledgeEditor.messages.createFailed'))
}
- MessagePlugin.success('知识库创建成功')
+ MessagePlugin.success(t('knowledgeEditor.messages.createSuccess'))
emit('success', result.data.id)
} else {
// 编辑模式:分别更新基本信息和配置
if (!props.kbId) {
- throw new Error('缺少知识库ID')
+ throw new Error(t('knowledgeEditor.messages.missingId'))
}
// 1. 更新基本信息(名称、描述)
@@ -473,14 +475,14 @@ const handleSubmit = async () => {
}
await updateKBConfig(props.kbId, config)
- MessagePlugin.success('配置保存成功')
+ MessagePlugin.success(t('knowledgeEditor.messages.updateSuccess'))
emit('success', props.kbId)
}
handleClose()
} catch (error: any) {
- console.error('操作失败:', error)
- MessagePlugin.error(error.message || '操作失败')
+ console.error('Knowledge base operation failed:', error)
+ MessagePlugin.error(error?.message || t('common.operationFailed'))
} finally {
saving.value = false
}
diff --git a/frontend/src/views/knowledge/KnowledgeBaseList.vue b/frontend/src/views/knowledge/KnowledgeBaseList.vue
index eab62b403..560d6237a 100644
--- a/frontend/src/views/knowledge/KnowledgeBaseList.vue
+++ b/frontend/src/views/knowledge/KnowledgeBaseList.vue
@@ -2,17 +2,17 @@
<div class="kb-list-container">
<!-- 头部 -->
<div class="header">
- <h2>知识库</h2>
+ <h2>{{ $t('knowledgeBase.title') }}</h2>
<button class="create-btn" @click="openCreateModal">
<t-icon name="add" size="16px" class="btn-icon" />
- <span>新建知识库</span>
+ <span>{{ $t('knowledgeList.create') }}</span>
</button>
</div>
<!-- 未初始化知识库提示 -->
<div v-if="hasUninitializedKbs" class="warning-banner">
<t-icon name="info-circle" size="16px" />
- <span>部分知识库尚未初始化,需要先在设置中配置模型信息才能添加知识文档</span>
+ <span>{{ $t('knowledgeList.uninitializedBanner') }}</span>
</div>
<!-- 卡片网格 -->
@@ -47,11 +47,11 @@
<div class="popup-menu" @click.stop>
<div class="popup-menu-item" @click.stop="handleSettings(kb)">
<t-icon class="menu-icon" name="setting" />
- <span>设置</span>
+ <span>{{ $t('knowledgeBase.settings') }}</span>
</div>
<div class="popup-menu-item delete" @click.stop="handleDelete(kb)">
<t-icon class="menu-icon" name="delete" />
- <span>删除</span>
+ <span>{{ $t('common.delete') }}</span>
</div>
</div>
</template>
@@ -61,7 +61,7 @@
<!-- 卡片内容 -->
<div class="card-content">
<div class="card-description">
- {{ kb.description || '暂无描述' }}
+ {{ kb.description || $t('knowledgeBase.noDescription') }}
</div>
</div>
@@ -69,7 +69,7 @@
<div class="card-bottom">
<div class="status-badge" :class="{ 'initialized': isInitialized(kb), 'uninitialized': !isInitialized(kb) }">
<span v-if="!isInitialized(kb)" class="warning-icon">⚠</span>
- <span>{{ isInitialized(kb) ? '已初始化' : '未初始化' }}</span>
+ <span>{{ isInitialized(kb) ? $t('knowledgeBase.initializedStatus') : $t('knowledgeBase.notInitializedStatus') }}</span>
</div>
<span class="card-time">{{ kb.updated_at }}</span>
</div>
@@ -79,8 +79,8 @@
<!-- 空状态 -->
<div v-else-if="!loading" class="empty-state">
<img class="empty-img" src="@/assets/img/upload.svg" alt="">
- <span class="empty-txt">暂无知识库</span>
- <span class="empty-desc">点击右上角"新建知识库"按钮创建第一个知识库</span>
+ <span class="empty-txt">{{ $t('knowledgeList.empty.title') }}</span>
+ <span class="empty-desc">{{ $t('knowledgeList.empty.description') }}</span>
</div>
@@ -95,14 +95,14 @@
<div class="circle-wrap">
<div class="dialog-header">
<img class="circle-img" src="@/assets/img/circle.png" alt="">
- <span class="circle-title">删除确认</span>
+ <span class="circle-title">{{ $t('knowledgeList.delete.confirmTitle') }}</span>
</div>
<span class="del-circle-txt">
- {{ `确认要删除知识库"${deletingKb?.name}"?删除后不可恢复` }}
+ {{ $t('knowledgeList.delete.confirmMessage', { name: deletingKb?.name ?? '' }) }}
</span>
<div class="circle-btn">
- <span class="circle-btn-txt" @click="deleteVisible = false">取消</span>
- <span class="circle-btn-txt confirm" @click="confirmDelete">确认删除</span>
+ <span class="circle-btn-txt" @click="deleteVisible = false">{{ $t('common.cancel') }}</span>
+ <span class="circle-btn-txt confirm" @click="confirmDelete">{{ $t('knowledgeList.delete.confirmButton') }}</span>
</div>
</div>
</t-dialog>
@@ -130,9 +130,11 @@ import { formatStringDate } from '@/utils/index'
import { useUIStore } from '@/stores/ui'
import KnowledgeBaseEditorModal from './KnowledgeBaseEditorModal.vue'
import Settings from '@/views/settings/Settings.vue'
+import { useI18n } from 'vue-i18n'
const router = useRouter()
const uiStore = useUIStore()
+const { t } = useI18n()
interface KB {
id: string;
@@ -203,15 +205,15 @@ const confirmDelete = () => {
deleteKnowledgeBase(deletingKb.value.id).then((res: any) => {
if (res.success) {
- MessagePlugin.success('已删除')
+ MessagePlugin.success(t('knowledgeList.messages.deleted'))
deleteVisible.value = false
deletingKb.value = null
fetchList()
} else {
- MessagePlugin.error(res.message || '删除失败')
+ MessagePlugin.error(res.message || t('knowledgeList.messages.deleteFailed'))
}
}).catch((e: any) => {
- MessagePlugin.error(e?.message || '删除失败')
+ MessagePlugin.error(e?.message || t('knowledgeList.messages.deleteFailed'))
})
}
@@ -244,7 +246,7 @@ const goSettings = (id: string) => {
// 知识库编辑器成功回调(创建或编辑成功)
const handleKBEditorSuccess = (kbId: string) => {
- console.log('知识库操作成功:', kbId)
+ console.log('[KnowledgeBaseList] knowledge operation success:', kbId)
fetchList()
}
</script>
@@ -407,6 +409,7 @@ const handleKBEditorSuccess = (kbId: string) => {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
+ line-clamp: 2;
overflow: hidden;
color: #00000066;
font-family: "PingFang SC";
diff --git a/frontend/src/views/knowledge/settings/KBAdvancedSettings.vue b/frontend/src/views/knowledge/settings/KBAdvancedSettings.vue
index 7544306cd..fdbb39c09 100644
--- a/frontend/src/views/knowledge/settings/KBAdvancedSettings.vue
+++ b/frontend/src/views/knowledge/settings/KBAdvancedSettings.vue
@@ -1,16 +1,16 @@
<template>
<div class="kb-advanced-settings">
<div class="section-header">
- <h2>高级设置</h2>
- <p class="section-description">配置多模态、知识图谱等高级功能</p>
+ <h2>{{ $t('knowledgeEditor.advanced.title') }}</h2>
+ <p class="section-description">{{ $t('knowledgeEditor.advanced.description') }}</p>
</div>
<div class="settings-group">
- <!-- 多模态功能 -->
+ <!-- Multimodal feature -->
<div class="setting-row">
<div class="setting-info">
- <label>多模态功能</label>
- <p class="desc">启用图片、视频等多模态内容的理解能力</p>
+ <label>{{ $t('knowledgeEditor.advanced.multimodal.label') }}</label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.description') }}</p>
</div>
<div class="setting-control">
<t-switch
@@ -21,13 +21,13 @@
</div>
</div>
- <!-- 多模态存储配置 -->
+ <!-- Multimodal storage configuration -->
<div v-if="localMultimodal.enabled" class="subsection">
- <!-- VLLM 视觉模型 -->
+ <!-- VLLM model -->
<div class="setting-row">
<div class="setting-info">
- <label>VLLM 视觉模型 <span class="required">*</span></label>
- <p class="desc">用于多模态理解的视觉语言模型(必选)</p>
+ <label>{{ $t('knowledgeEditor.advanced.multimodal.vllmLabel') }} <span class="required">*</span></label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.vllmDescription') }}</p>
</div>
<div class="setting-control">
<ModelSelector
@@ -37,39 +37,39 @@
:all-models="allModels"
@update:selected-model-id="handleVLLMChange"
@add-model="handleAddModel('vllm')"
- placeholder="请选择VLLM模型(必选)"
+ :placeholder="$t('knowledgeEditor.advanced.multimodal.vllmPlaceholder')"
/>
</div>
</div>
<div class="subsection-header">
- <h4>存储配置 <span class="required">*</span></h4>
+ <h4>{{ $t('knowledgeEditor.advanced.multimodal.storageTitle') }} <span class="required">*</span></h4>
</div>
<div class="setting-row">
<div class="setting-info">
- <label>存储类型 <span class="required">*</span></label>
- <p class="desc">选择多模态文件的存储方式(MinIO或腾讯云COS二选一)</p>
+ <label>{{ $t('knowledgeEditor.advanced.multimodal.storageTypeLabel') }} <span class="required">*</span></label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.storageTypeDescription') }}</p>
</div>
<div class="setting-control">
<t-radio-group v-model="localMultimodal.storageType" @change="handleStorageTypeChange">
- <t-radio value="minio">MinIO</t-radio>
- <t-radio value="cos">腾讯云COS</t-radio>
+ <t-radio value="minio">{{ $t('knowledgeEditor.advanced.multimodal.storageTypeOptions.minio') }}</t-radio>
+ <t-radio value="cos">{{ $t('knowledgeEditor.advanced.multimodal.storageTypeOptions.cos') }}</t-radio>
</t-radio-group>
</div>
</div>
- <!-- MinIO配置 -->
+ <!-- MinIO configuration -->
<div v-if="localMultimodal.storageType === 'minio'" class="storage-config">
<div class="setting-row">
<div class="setting-info">
- <label>Bucket名称 <span class="required">*</span></label>
- <p class="desc">MinIO存储桶名称(必填)</p>
+ <label>{{ $t('knowledgeEditor.advanced.multimodal.minio.bucketLabel') }} <span class="required">*</span></label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.minio.bucketDescription') }}</p>
</div>
<div class="setting-control">
<t-input
v-model="localMultimodal.minio.bucketName"
- placeholder="请输入Bucket名称(必填)"
+ :placeholder="$t('knowledgeEditor.advanced.multimodal.minio.bucketPlaceholder')"
@change="handleConfigChange"
style="width: 280px;"
/>
@@ -78,8 +78,8 @@
<div class="setting-row">
<div class="setting-info">
- <label>使用SSL</label>
- <p class="desc">是否使用SSL连接</p>
+ <label>{{ $t('knowledgeEditor.advanced.multimodal.minio.useSslLabel') }}</label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.minio.useSslDescription') }}</p>
</div>
<div class="setting-control">
<t-switch
@@ -92,13 +92,13 @@
<div class="setting-row">
<div class="setting-info">
- <label>路径前缀</label>
- <p class="desc">文件存储路径前缀(可选)</p>
+ <label>{{ $t('knowledgeEditor.advanced.multimodal.minio.pathPrefixLabel') }}</label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.minio.pathPrefixDescription') }}</p>
</div>
<div class="setting-control">
<t-input
v-model="localMultimodal.minio.pathPrefix"
- placeholder="请输入路径前缀"
+ :placeholder="$t('knowledgeEditor.advanced.multimodal.minio.pathPrefixPlaceholder')"
@change="handleConfigChange"
style="width: 280px;"
/>
@@ -106,17 +106,17 @@
</div>
</div>
- <!-- COS配置 -->
+ <!-- COS configuration -->
<div v-if="localMultimodal.storageType === 'cos'" class="storage-config">
<div class="setting-row">
<div class="setting-info">
- <label>SecretId <span class="required">*</span></label>
- <p class="desc">腾讯云API密钥ID(必填)</p>
+ <label>{{ $t('knowledgeEditor.advanced.multimodal.cos.secretIdLabel') }} <span class="required">*</span></label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.cos.secretIdDescription') }}</p>
</div>
<div class="setting-control">
<t-input
v-model="localMultimodal.cos.secretId"
- placeholder="请输入SecretId(必填)"
+ :placeholder="$t('knowledgeEditor.advanced.multimodal.cos.secretIdPlaceholder')"
@change="handleConfigChange"
style="width: 280px;"
/>
@@ -125,14 +125,14 @@
<div class="setting-row">
<div class="setting-info">
- <label>SecretKey <span class="required">*</span></label>
- <p class="desc">腾讯云API密钥Key(必填)</p>
+ <label>{{ $t('knowledgeEditor.advanced.multimodal.cos.secretKeyLabel') }} <span class="required">*</span></label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.cos.secretKeyDescription') }}</p>
</div>
<div class="setting-control">
<t-input
v-model="localMultimodal.cos.secretKey"
type="password"
- placeholder="请输入SecretKey(必填)"
+ :placeholder="$t('knowledgeEditor.advanced.multimodal.cos.secretKeyPlaceholder')"
@change="handleConfigChange"
style="width: 280px;"
/>
@@ -141,13 +141,13 @@
<div class="setting-row">
<div class="setting-info">
- <label>地域 <span class="required">*</span></label>
- <p class="desc">COS存储桶所在地域(必填)</p>
+ <label>{{ $t('knowledgeEditor.advanced.multimodal.cos.regionLabel') }} <span class="required">*</span></label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.cos.regionDescription') }}</p>
</div>
<div class="setting-control">
<t-input
v-model="localMultimodal.cos.region"
- placeholder="如:ap-guangzhou(必填)"
+ :placeholder="$t('knowledgeEditor.advanced.multimodal.cos.regionPlaceholder')"
@change="handleConfigChange"
style="width: 280px;"
/>
@@ -156,13 +156,13 @@
<div class="setting-row">
<div class="setting-info">
- <label>Bucket名称 <span class="required">*</span></label>
- <p class="desc">COS存储桶名称(必填)</p>
+ <label>{{ $t('knowledgeEditor.advanced.multimodal.cos.bucketLabel') }} <span class="required">*</span></label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.cos.bucketDescription') }}</p>
</div>
<div class="setting-control">
<t-input
v-model="localMultimodal.cos.bucketName"
- placeholder="请输入Bucket名称(必填)"
+ :placeholder="$t('knowledgeEditor.advanced.multimodal.cos.bucketPlaceholder')"
@change="handleConfigChange"
style="width: 280px;"
/>
@@ -171,13 +171,13 @@
<div class="setting-row">
<div class="setting-info">
- <label>AppId <span class="required">*</span></label>
- <p class="desc">腾讯云应用ID(必填)</p>
+ <label>{{ $t('knowledgeEditor.advanced.multimodal.cos.appIdLabel') }} <span class="required">*</span></label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.cos.appIdDescription') }}</p>
</div>
<div class="setting-control">
<t-input
v-model="localMultimodal.cos.appId"
- placeholder="请输入AppId(必填)"
+ :placeholder="$t('knowledgeEditor.advanced.multimodal.cos.appIdPlaceholder')"
@change="handleConfigChange"
style="width: 280px;"
/>
@@ -186,13 +186,13 @@
<div class="setting-row">
<div class="setting-info">
- <label>路径前缀</label>
- <p class="desc">文件存储路径前缀(可选)</p>
+ <label>{{ $t('knowledgeEditor.advanced.multimodal.cos.pathPrefixLabel') }}</label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.multimodal.cos.pathPrefixDescription') }}</p>
</div>
<div class="setting-control">
<t-input
v-model="localMultimodal.cos.pathPrefix"
- placeholder="请输入路径前缀"
+ :placeholder="$t('knowledgeEditor.advanced.multimodal.cos.pathPrefixPlaceholder')"
@change="handleConfigChange"
style="width: 280px;"
/>
@@ -201,11 +201,11 @@
</div>
</div>
- <!-- 知识图谱提取 -->
+ <!-- Knowledge graph extraction -->
<div class="setting-row">
<div class="setting-info">
- <label>知识图谱提取</label>
- <p class="desc">从文档中自动提取实体和关系构建知识图谱</p>
+ <label>{{ $t('knowledgeEditor.advanced.graph.label') }}</label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.graph.description') }}</p>
</div>
<div class="setting-control">
<t-switch
@@ -216,21 +216,21 @@
</div>
</div>
- <!-- 知识图谱配置 -->
+ <!-- Knowledge graph configuration -->
<div v-if="localNodeExtract.enabled" class="subsection">
<div class="subsection-header">
- <h4>图谱配置</h4>
+ <h4>{{ $t('knowledgeEditor.advanced.graph.configTitle') }}</h4>
</div>
<div class="setting-row">
<div class="setting-info">
- <label>提示文本</label>
- <p class="desc">用于引导模型提取实体和关系的提示文本</p>
+ <label>{{ $t('knowledgeEditor.advanced.graph.promptLabel') }}</label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.graph.promptDescription') }}</p>
</div>
<div class="setting-control">
<t-textarea
v-model="localNodeExtract.text"
- placeholder="请输入提示文本"
+ :placeholder="$t('knowledgeEditor.advanced.graph.promptPlaceholder')"
:autosize="{ minRows: 3, maxRows: 6 }"
@change="handleConfigChange"
style="width: 280px;"
@@ -240,13 +240,13 @@
<div class="setting-row">
<div class="setting-info">
- <label>标签</label>
- <p class="desc">预定义的实体标签(多个标签用逗号分隔)</p>
+ <label>{{ $t('knowledgeEditor.advanced.graph.tagsLabel') }}</label>
+ <p class="desc">{{ $t('knowledgeEditor.advanced.graph.tagsDescription') }}</p>
</div>
<div class="setting-control">
<t-tag-input
v-model="localNodeExtract.tags"
- placeholder="输入标签后按回车"
+ :placeholder="$t('knowledgeEditor.advanced.graph.tagsPlaceholder')"
@change="handleConfigChange"
style="width: 280px;"
/>
@@ -307,7 +307,7 @@ const localNodeExtract = ref<NodeExtractConfig>({ ...props.nodeExtract })
const vllmSelectorRef = ref()
-// 监听props变化
+// Watch for prop changes
watch(() => props.multimodal, (newVal) => {
localMultimodal.value = { ...newVal }
}, { deep: true })
@@ -316,9 +316,9 @@ watch(() => props.nodeExtract, (newVal) => {
localNodeExtract.value = { ...newVal }
}, { deep: true })
-// 处理多模态开关
+// Handle multimodal toggle
const handleMultimodalToggle = () => {
- // 如果关闭多模态,清空相关配置
+ // Reset related configuration when multimodal is disabled
if (!localMultimodal.value.enabled) {
localMultimodal.value.vllmModelId = ''
localMultimodal.value.minio = {
@@ -338,34 +338,34 @@ const handleMultimodalToggle = () => {
emit('update:multimodal', localMultimodal.value)
}
-// 处理存储类型变化
+// Handle storage type change
const handleStorageTypeChange = () => {
emit('update:multimodal', localMultimodal.value)
}
-// 处理VLLM模型变化
+// Handle VLLM model change
const handleVLLMChange = (modelId: string) => {
localMultimodal.value.vllmModelId = modelId
emit('update:multimodal', localMultimodal.value)
}
-// 处理添加模型
+// Navigate to model management when adding models
const handleAddModel = (subSection: string) => {
uiStore.openSettings('models', subSection)
}
-// 处理知识图谱开关
+// Handle knowledge graph toggle
const handleNodeExtractToggle = () => {
emit('update:nodeExtract', localNodeExtract.value)
}
-// 处理配置变化
+// Handle configuration change
const handleConfigChange = () => {
emit('update:multimodal', localMultimodal.value)
emit('update:nodeExtract', localNodeExtract.value)
}
-// 由于使用了 allModels prop,不再需要单独刷新
+// The allModels prop keeps model options in sync
</script>
<style lang="less" scoped>
diff --git a/frontend/src/views/knowledge/settings/KBChunkingSettings.vue b/frontend/src/views/knowledge/settings/KBChunkingSettings.vue
index ec3f2c6e4..bee4bb0b4 100644
--- a/frontend/src/views/knowledge/settings/KBChunkingSettings.vue
+++ b/frontend/src/views/knowledge/settings/KBChunkingSettings.vue
@@ -1,16 +1,16 @@
<template>
<div class="kb-chunking-settings">
<div class="section-header">
- <h2>分块设置</h2>
- <p class="section-description">配置文档分块参数,优化检索效果</p>
+ <h2>{{ $t('knowledgeEditor.chunking.title') }}</h2>
+ <p class="section-description">{{ $t('knowledgeEditor.chunking.description') }}</p>
</div>
<div class="settings-group">
<!-- Chunk Size -->
<div class="setting-row">
<div class="setting-info">
- <label>分块大小</label>
- <p class="desc">控制每个文档分块的字符数(100-4000)</p>
+ <label>{{ $t('knowledgeEditor.chunking.sizeLabel') }}</label>
+ <p class="desc">{{ $t('knowledgeEditor.chunking.sizeDescription') }}</p>
</div>
<div class="setting-control">
<div class="slider-container">
@@ -23,7 +23,7 @@
@change="handleChunkSizeChange"
style="width: 200px;"
/>
- <span class="value-display">{{ localChunkSize }} 字符</span>
+ <span class="value-display">{{ localChunkSize }} {{ $t('knowledgeEditor.chunking.characters') }}</span>
</div>
</div>
</div>
@@ -31,8 +31,8 @@
<!-- Chunk Overlap -->
<div class="setting-row">
<div class="setting-info">
- <label>分块重叠</label>
- <p class="desc">相邻文档块之间的重叠字符数(0-500)</p>
+ <label>{{ $t('knowledgeEditor.chunking.overlapLabel') }}</label>
+ <p class="desc">{{ $t('knowledgeEditor.chunking.overlapDescription') }}</p>
</div>
<div class="setting-control">
<div class="slider-container">
@@ -45,23 +45,23 @@
@change="handleChunkOverlapChange"
style="width: 200px;"
/>
- <span class="value-display">{{ localChunkOverlap }} 字符</span>
+ <span class="value-display">{{ localChunkOverlap }} {{ $t('knowledgeEditor.chunking.characters') }}</span>
</div>
</div>
</div>
- <!-- 分隔符 -->
+ <!-- Separators -->
<div class="setting-row">
<div class="setting-info">
- <label>分隔符</label>
- <p class="desc">文档分块时使用的分隔符</p>
+ <label>{{ $t('knowledgeEditor.chunking.separatorsLabel') }}</label>
+ <p class="desc">{{ $t('knowledgeEditor.chunking.separatorsDescription') }}</p>
</div>
<div class="setting-control">
<t-select
v-model="localSeparators"
:options="separatorOptions"
multiple
- placeholder="选择分隔符"
+ :placeholder="$t('knowledgeEditor.chunking.separatorsPlaceholder')"
@change="handleSeparatorsChange"
style="width: 280px;"
/>
@@ -72,7 +72,8 @@
</template>
<script setup lang="ts">
-import { ref, watch } from 'vue'
+import { ref, watch, computed } from 'vue'
+import { useI18n } from 'vue-i18n'
interface ChunkingConfig {
chunkSize: number
@@ -93,42 +94,43 @@ const emit = defineEmits<{
const localChunkSize = ref(props.config.chunkSize)
const localChunkOverlap = ref(props.config.chunkOverlap)
const localSeparators = ref([...props.config.separators])
-
-// 分隔符选项
-const separatorOptions = [
- { label: '双换行 (\\n\\n)', value: '\n\n' },
- { label: '单换行 (\\n)', value: '\n' },
- { label: '中文句号 (。)', value: '。' },
- { label: '感叹号 (!)', value: '!' },
- { label: '问号 (?)', value: '?' },
- { label: '中文分号 (;)', value: ';' },
- { label: '英文分号 (;)', value: ';' },
- { label: '空格 ( )', value: ' ' }
-]
-
-// 监听props变化
+const { t } = useI18n()
+
+// Separator options
+const separatorOptions = computed(() => [
+ { label: t('knowledgeEditor.chunking.separators.doubleNewline'), value: '\n\n' },
+ { label: t('knowledgeEditor.chunking.separators.singleNewline'), value: '\n' },
+ { label: t('knowledgeEditor.chunking.separators.periodCn'), value: '。' },
+ { label: t('knowledgeEditor.chunking.separators.exclamationCn'), value: '!' },
+ { label: t('knowledgeEditor.chunking.separators.questionCn'), value: '?' },
+ { label: t('knowledgeEditor.chunking.separators.semicolonCn'), value: ';' },
+ { label: t('knowledgeEditor.chunking.separators.semicolonEn'), value: ';' },
+ { label: t('knowledgeEditor.chunking.separators.space'), value: ' ' }
+])
+
+// Watch for prop changes
watch(() => props.config, (newConfig) => {
localChunkSize.value = newConfig.chunkSize
localChunkOverlap.value = newConfig.chunkOverlap
localSeparators.value = [...newConfig.separators]
}, { deep: true })
-// 处理分块大小变化
+// Handle chunk size change
const handleChunkSizeChange = () => {
emitUpdate()
}
-// 处理分块重叠变化
+// Handle chunk overlap change
const handleChunkOverlapChange = () => {
emitUpdate()
}
-// 处理分隔符变化
+// Handle separator change
const handleSeparatorsChange = () => {
emitUpdate()
}
-// 发出更新事件
+// Emit update event
const emitUpdate = () => {
emit('update:config', {
chunkSize: localChunkSize.value,
diff --git a/frontend/src/views/knowledge/settings/KBModelConfig.vue b/frontend/src/views/knowledge/settings/KBModelConfig.vue
index 581e1da27..e12ff5d13 100644
--- a/frontend/src/views/knowledge/settings/KBModelConfig.vue
+++ b/frontend/src/views/knowledge/settings/KBModelConfig.vue
@@ -1,16 +1,16 @@
<template>
<div class="kb-model-config">
<div class="section-header">
- <h2>模型配置</h2>
- <p class="section-description">为知识库选择合适的AI模型</p>
+ <h2>{{ $t('knowledgeEditor.models.title') }}</h2>
+ <p class="section-description">{{ $t('knowledgeEditor.models.description') }}</p>
</div>
<div class="settings-group">
<!-- LLM 大语言模型 -->
<div class="setting-row">
<div class="setting-info">
- <label>LLM 大语言模型 <span class="required">*</span></label>
- <p class="desc">用于对话和问答的大语言模型</p>
+ <label>{{ $t('knowledgeEditor.models.llmLabel') }} <span class="required">*</span></label>
+ <p class="desc">{{ $t('knowledgeEditor.models.llmDesc') }}</p>
</div>
<div class="setting-control">
<ModelSelector
@@ -20,7 +20,7 @@
:all-models="allModels"
@update:selected-model-id="handleLLMChange"
@add-model="handleAddModel('chat')"
- placeholder="请选择LLM模型"
+ :placeholder="$t('knowledgeEditor.models.llmPlaceholder')"
/>
</div>
</div>
@@ -28,12 +28,12 @@
<!-- Embedding 嵌入模型 -->
<div class="setting-row">
<div class="setting-info">
- <label>Embedding 嵌入模型 <span class="required">*</span></label>
- <p class="desc">用于文本向量化的嵌入模型</p>
+ <label>{{ $t('knowledgeEditor.models.embeddingLabel') }} <span class="required">*</span></label>
+ <p class="desc">{{ $t('knowledgeEditor.models.embeddingDesc') }}</p>
<t-alert
v-if="hasFiles"
theme="warning"
- message="知识库中已有文件,无法修改Embedding模型"
+ :message="$t('knowledgeEditor.models.embeddingLocked')"
style="margin-top: 8px;"
/>
</div>
@@ -46,7 +46,7 @@
:disabled="hasFiles"
@update:selected-model-id="handleEmbeddingChange"
@add-model="handleAddModel('embedding')"
- placeholder="请选择Embedding模型"
+ :placeholder="$t('knowledgeEditor.models.embeddingPlaceholder')"
/>
</div>
</div>
@@ -54,8 +54,8 @@
<!-- ReRank 重排序模型 -->
<div class="setting-row">
<div class="setting-info">
- <label>ReRank 重排序模型</label>
- <p class="desc">用于搜索结果重排序的模型(可选)</p>
+ <label>{{ $t('knowledgeEditor.models.rerankLabel') }}</label>
+ <p class="desc">{{ $t('knowledgeEditor.models.rerankDesc') }}</p>
</div>
<div class="setting-control">
<ModelSelector
@@ -65,7 +65,7 @@
:all-models="allModels"
@update:selected-model-id="handleRerankChange"
@add-model="handleAddModel('rerank')"
- placeholder="请选择ReRank模型(可选)"
+ :placeholder="$t('knowledgeEditor.models.rerankPlaceholder')"
/>
</div>
</div>
@@ -76,9 +76,9 @@
<script setup lang="ts">
import { ref } from 'vue'
-import { MessagePlugin } from 'tdesign-vue-next'
import { useUIStore } from '@/stores/ui'
import ModelSelector from '@/components/ModelSelector.vue'
+import { useI18n } from 'vue-i18n'
interface ModelConfig {
llmModelId?: string
@@ -100,6 +100,7 @@ const emit = defineEmits<{
}>()
const uiStore = useUIStore()
+const { t } = useI18n()
// 引用各个模型选择器
const llmSelectorRef = ref<InstanceType<typeof ModelSelector>>()
diff --git a/frontend/src/views/platform/index.vue b/frontend/src/views/platform/index.vue
index 8ce426e40..1e5c214c4 100644
--- a/frontend/src/views/platform/index.vue
+++ b/frontend/src/views/platform/index.vue
@@ -16,11 +16,13 @@ import useKnowledgeBase from '@/hooks/useKnowledgeBase'
import UploadMask from '@/components/upload-mask.vue'
import { getKnowledgeBaseById } from '@/api/knowledge-base/index'
import { MessagePlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
let { requestMethod } = useKnowledgeBase()
const route = useRoute();
let ismask = ref(false)
let uploadInput = ref();
+const { t } = useI18n();
// 获取当前知识库ID
const getCurrentKbId = (): string | null => {
@@ -32,7 +34,7 @@ const checkKnowledgeBaseInitialization = async (): Promise<boolean> => {
const currentKbId = getCurrentKbId();
if (!currentKbId) {
- MessagePlugin.error("缺少知识库ID");
+ MessagePlugin.error(t('knowledgeBase.missingId'));
return false;
}
@@ -41,12 +43,12 @@ const checkKnowledgeBaseInitialization = async (): Promise<boolean> => {
const kb = kbResponse.data;
if (!kb.embedding_model_id || !kb.summary_model_id) {
- MessagePlugin.warning("该知识库尚未完成初始化配置,请先前往设置页面配置模型信息后再上传文件");
+ MessagePlugin.warning(t('knowledgeBase.notInitialized'));
return false;
}
return true;
} catch (error) {
- MessagePlugin.error("获取知识库信息失败,无法上传文件");
+ MessagePlugin.error(t('knowledgeBase.getInfoFailed'));
return false;
}
}
@@ -91,7 +93,7 @@ const handleGlobalDrop = async (event: DragEvent) => {
}
});
} else {
- MessagePlugin.warning('请拖拽文件而不是文本或链接');
+ MessagePlugin.warning(t('knowledgeBase.dragFileNotText'));
}
}
diff --git a/frontend/src/views/settings/AgentSettings.vue b/frontend/src/views/settings/AgentSettings.vue
index 452aabc00..d7a738c09 100644
--- a/frontend/src/views/settings/AgentSettings.vue
+++ b/frontend/src/views/settings/AgentSettings.vue
@@ -1,13 +1,13 @@
<template>
<div class="agent-settings">
<div class="section-header">
- <h2>Agent 配置</h2>
- <p class="section-description">配置 AI Agent 的默认行为和参数,这些设置将应用于所有启用 Agent 模式的对话</p>
+ <h2>{{ $t('agentSettings.title') }}</h2>
+ <p class="section-description">{{ $t('agentSettings.description') }}</p>
<!-- Agent 状态显示 -->
<div class="agent-status-row">
<div class="status-label">
- <label>Agent 状态</label>
+ <label>{{ $t('agentSettings.status.label') }}</label>
</div>
<div class="status-control">
<div class="status-badge" :class="{ ready: isAgentReady }">
@@ -22,7 +22,7 @@
class="status-icon"
/>
<span class="status-text">
- {{ isAgentReady ? '可用' : '未就绪' }}
+ {{ isAgentReady ? $t('agentSettings.status.ready') : $t('agentSettings.status.notReady') }}
</span>
</div>
<span v-if="!isAgentReady" class="status-hint">
@@ -30,7 +30,7 @@
</span>
<p v-if="!isAgentReady" class="status-tip">
<t-icon name="info-circle" class="tip-icon" />
- 配置完成后,Agent 状态将自动变为"可用",此时可在对话界面开启 Agent 模式
+ {{ $t('agentSettings.status.hint') }}
</p>
</div>
</div>
@@ -41,8 +41,8 @@
<!-- 最大迭代次数 -->
<div class="setting-row">
<div class="setting-info">
- <label>最大迭代次数</label>
- <p class="desc">Agent 执行任务时的最大推理步骤数</p>
+ <label>{{ $t('agentSettings.maxIterations.label') }}</label>
+ <p class="desc">{{ $t('agentSettings.maxIterations.desc') }}</p>
</div>
<div class="setting-control">
<div class="slider-with-value">
@@ -63,11 +63,11 @@
<!-- 思考模型 -->
<div class="setting-row">
<div class="setting-info">
- <label>思考模型</label>
- <p class="desc">用于 Agent 推理和规划的 LLM 模型</p>
+ <label>{{ $t('agentSettings.thinkingModel.label') }}</label>
+ <p class="desc">{{ $t('agentSettings.thinkingModel.desc') }}</p>
<p class="hint-tip">
<t-icon name="info-circle" class="tip-icon" />
- 需要支持 Function call 的大尺寸模型,如 deepseek-v3.1-termius
+ {{ $t('agentSettings.thinkingModel.hint') }}
</p>
</div>
<div class="setting-control">
@@ -75,7 +75,7 @@
v-model="localThinkingModelId"
:loading="loadingModels"
filterable
- placeholder="搜索模型..."
+ :placeholder="$t('agentSettings.model.placeholder')"
@change="handleThinkingModelChange"
@focus="loadAllModels"
style="width: 280px;"
@@ -90,7 +90,7 @@
<div class="model-option">
<t-icon name="check-circle-filled" class="model-icon" />
<span class="model-name">{{ model.name }}</span>
- <t-tag v-if="model.is_default" size="small" theme="success">默认</t-tag>
+ <t-tag v-if="model.is_default" size="small" theme="success">{{ $t('common.default') }}</t-tag>
</div>
</t-option>
@@ -98,7 +98,7 @@
<t-option value="__add_model__" class="add-model-option">
<div class="model-option add">
<t-icon name="add" class="add-icon" />
- <span class="model-name">添加新的对话模型</span>
+ <span class="model-name">{{ $t('agentSettings.model.addChat') }}</span>
</div>
</t-option>
</t-select>
@@ -108,15 +108,15 @@
<!-- Rerank 模型 -->
<div class="setting-row">
<div class="setting-info">
- <label>Rerank 模型</label>
- <p class="desc">搜索结果重排序,统一不同来源的相关度分数</p>
+ <label>{{ $t('agentSettings.rerankModel.label') }}</label>
+ <p class="desc">{{ $t('agentSettings.rerankModel.desc') }}</p>
</div>
<div class="setting-control">
<t-select
v-model="localRerankModelId"
:loading="loadingModels"
filterable
- placeholder="搜索模型..."
+ :placeholder="$t('agentSettings.model.placeholder')"
@change="handleRerankModelChange"
@focus="loadAllModels"
style="width: 280px;"
@@ -131,7 +131,7 @@
<div class="model-option">
<t-icon name="check-circle-filled" class="model-icon" />
<span class="model-name">{{ model.name }}</span>
- <t-tag v-if="model.is_default" size="small" theme="success">默认</t-tag>
+ <t-tag v-if="model.is_default" size="small" theme="success">{{ $t('common.default') }}</t-tag>
</div>
</t-option>
@@ -139,7 +139,7 @@
<t-option value="__add_model__" class="add-model-option">
<div class="model-option add">
<t-icon name="add" class="add-icon" />
- <span class="model-name">添加新的 Rerank 模型</span>
+ <span class="model-name">{{ $t('agentSettings.model.addRerank') }}</span>
</div>
</t-option>
</t-select>
@@ -149,8 +149,8 @@
<!-- 温度参数 -->
<div class="setting-row">
<div class="setting-info">
- <label>温度参数</label>
- <p class="desc">控制模型输出的随机性,0 最确定,1 最随机</p>
+ <label>{{ $t('agentSettings.temperature.label') }}</label>
+ <p class="desc">{{ $t('agentSettings.temperature.desc') }}</p>
</div>
<div class="setting-control">
<div class="slider-with-value">
@@ -171,14 +171,14 @@
<!-- 允许的工具 -->
<div class="setting-row">
<div class="setting-info">
- <label>允许的工具</label>
- <p class="desc">选择 Agent 可以使用的工具,至少选择一个</p>
+ <label>{{ $t('agentSettings.allowedTools.label') }}</label>
+ <p class="desc">{{ $t('agentSettings.allowedTools.desc') }}</p>
</div>
<div class="setting-control">
<t-select
v-model="localAllowedTools"
multiple
- placeholder="请选择工具..."
+ :placeholder="$t('agentSettings.allowedTools.placeholder')"
@change="handleAllowedToolsChange"
style="width: 400px;"
>
@@ -198,25 +198,25 @@
<!-- 系统 Prompt -->
<div class="setting-row vertical">
<div class="setting-info">
- <label>系统 Prompt</label>
- <p class="desc">配置 Agent 的系统提示词,支持占位符模板。占位符会在运行时自动替换为实际内容。</p>
+ <label>{{ $t('agentSettings.systemPrompt.label') }}</label>
+ <p class="desc">{{ $t('agentSettings.systemPrompt.desc') }}</p>
<div class="placeholder-hint">
- <p class="hint-title">可用占位符:</p>
+ <p class="hint-title">{{ $t('agentSettings.systemPrompt.availablePlaceholders') }}</p>
<ul class="placeholder-list">
<li v-for="placeholder in availablePlaceholders" :key="placeholder.name">
<code v-html="`{{${placeholder.name}}}`"></code> - {{ placeholder.label }}({{ placeholder.description }})
</li>
</ul>
- <p class="hint-tip">提示:输入 <code>&#123;&#123;</code> 时会自动显示可用占位符</p>
+ <p class="hint-tip">{{ $t('agentSettings.systemPrompt.hintPrefix') }} <code>&#123;&#123;</code> {{ $t('agentSettings.systemPrompt.hintSuffix') }}</p>
</div>
</div>
<div class="setting-control full-width" style="position: relative;">
<div class="prompt-header">
<div class="prompt-toggle">
- <span class="prompt-toggle-label">自定义 Prompt</span>
+ <span class="prompt-toggle-label">{{ $t('agentSettings.systemPrompt.custom') }}</span>
<t-switch
v-model="localUseCustomSystemPrompt"
- :label="['关闭', '开启']"
+ :label="[$t('common.off'), $t('common.on')]"
size="large"
@change="handleUseCustomPromptToggle"
/>
@@ -228,18 +228,18 @@
@click="handleResetToDefault"
:loading="isResettingPrompt"
>
- 恢复默认
+ {{ $t('common.resetToDefault') }}
</t-button>
</div>
<p v-if="!localUseCustomSystemPrompt" class="prompt-disabled-hint">
- 当前使用系统默认 Prompt,开启自定义后才会应用下方内容。
+ {{ $t('agentSettings.systemPrompt.disabledHint') }}
</p>
<div class="prompt-textarea-wrapper">
<t-textarea
ref="promptTextareaRef"
v-model="localSystemPrompt"
:autosize="{ minRows: 15, maxRows: 30 }"
- placeholder="请输入系统 Prompt,或留空使用默认 Prompt..."
+ :placeholder="$t('agentSettings.systemPrompt.placeholder')"
@blur="handleSystemPromptChange"
@input="handlePromptInput"
@keydown="handlePromptKeydown"
@@ -279,11 +279,13 @@ import { ref, onMounted, watch, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useSettingsStore } from '@/stores/settings'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
import { listModels, type ModelConfig } from '@/api/model'
import { getAgentConfig, updateAgentConfig, type AgentConfig, type ToolDefinition, type PlaceholderDefinition } from '@/api/system'
const settingsStore = useSettingsStore()
const router = useRouter()
+const { t } = useI18n()
// 本地状态
const localMaxIterations = ref(5)
@@ -307,20 +309,20 @@ const agentStatusMessage = computed(() => {
const missing: string[] = []
if (!localThinkingModelId.value) {
- missing.push('思考模型')
+ missing.push(t('agentSettings.status.missingThinkingModel'))
}
if (!localRerankModelId.value) {
- missing.push('Rerank 模型')
+ missing.push(t('agentSettings.status.missingRerankModel'))
}
if (localAllowedTools.value.length === 0) {
- missing.push('允许的工具')
+ missing.push(t('agentSettings.status.missingAllowedTools'))
}
if (missing.length === 0) {
return ''
}
- return `请配置${missing.join('、')}`
+ return t('agentSettings.status.pleaseConfigure', { items: missing.join('、') })
})
// 模型列表状态
@@ -528,17 +530,17 @@ const getErrorMessage = (error: any): string => {
switch (errorCode) {
case 2100:
- return '启用Agent模式前,请先选择思考模型'
+ return t('agentSettings.errors.selectThinkingModel')
case 2101:
- return '至少需要选择一个允许的工具'
+ return t('agentSettings.errors.selectAtLeastOneTool')
case 2102:
- return '最大迭代次数必须在1-20之间'
+ return t('agentSettings.errors.iterationsRange')
case 2103:
- return '温度参数必须在0-2之间'
+ return t('agentSettings.errors.temperatureRange')
case 1010:
- return errorMessage || '配置验证失败'
+ return errorMessage || t('agentSettings.errors.validationFailed')
default:
- return errorMessage || '保存失败,请重试'
+ return errorMessage || t('common.saveFailed')
}
}
@@ -593,7 +595,7 @@ const handleMaxIterationsChangeDebounced = (value: number) => {
await updateAgentConfig(config)
settingsStore.updateAgentConfig({ maxIterations: numValue })
lastSavedValue = numValue // 记录已保存的值
- MessagePlugin.success('最大迭代次数已保存')
+ MessagePlugin.success(t('agentSettings.toasts.iterationsSaved'))
} catch (error) {
console.error('保存失败:', error)
MessagePlugin.error(getErrorMessage(error))
@@ -658,7 +660,7 @@ const handleThinkingModelChange = async (value: string) => {
await updateAgentConfig(config)
// 更新 store,确保 isAgentReady 能正确计算
settingsStore.updateAgentConfig({ thinkingModelId: value })
- MessagePlugin.success('思考模型已保存')
+ MessagePlugin.success(t('agentSettings.toasts.thinkingModelSaved'))
} catch (error) {
console.error('保存失败:', error)
MessagePlugin.error(getErrorMessage(error))
@@ -692,7 +694,7 @@ const handleRerankModelChange = async (value: string) => {
await updateAgentConfig(config)
settingsStore.updateAgentConfig({ rerankModelId: value })
- MessagePlugin.success('Rerank 模型已保存')
+ MessagePlugin.success(t('agentSettings.toasts.rerankModelSaved'))
} catch (error) {
console.error('保存失败:', error)
MessagePlugin.error(getErrorMessage(error))
@@ -774,7 +776,7 @@ const handleTemperatureChange = async (value: number) => {
await updateAgentConfig(config)
settingsStore.updateAgentConfig({ temperature: value })
- MessagePlugin.success('温度参数已保存')
+ MessagePlugin.success(t('agentSettings.toasts.temperatureSaved'))
} catch (error) {
console.error('保存失败:', error)
MessagePlugin.error(getErrorMessage(error))
@@ -801,7 +803,7 @@ const handleAllowedToolsChange = async (value: string[]) => {
await updateAgentConfig(config)
settingsStore.updateAgentConfig({ allowedTools: value })
- MessagePlugin.success('工具配置已更新')
+ MessagePlugin.success(t('agentSettings.toasts.toolsUpdated'))
} catch (error) {
console.error('保存工具配置失败:', error)
MessagePlugin.error(getErrorMessage(error))
@@ -831,7 +833,7 @@ const handleUseCustomPromptToggle = async (value: boolean) => {
await updateAgentConfig(config)
savedUseCustomSystemPrompt = value
- MessagePlugin.success(value ? '已启用自定义 Prompt' : '已切换为默认 Prompt')
+ MessagePlugin.success(value ? t('agentSettings.toasts.customPromptEnabled') : t('agentSettings.toasts.defaultPromptEnabled'))
} catch (error) {
console.error('切换自定义 Prompt 失败:', error)
MessagePlugin.error(getErrorMessage(error))
@@ -1034,10 +1036,10 @@ const insertPlaceholder = (placeholderName: string) => {
// 恢复默认 Prompt
const handleResetToDefault = async () => {
const confirmDialog = DialogPlugin.confirm({
- header: '恢复默认 Prompt',
- body: '确定要恢复为默认 Prompt 吗?当前的自定义 Prompt 将被覆盖。',
- confirmBtn: '确定',
- cancelBtn: '取消',
+ header: t('agentSettings.reset.header'),
+ body: t('agentSettings.reset.body'),
+ confirmBtn: t('common.confirm'),
+ cancelBtn: t('common.cancel'),
onConfirm: async () => {
try {
isResettingPrompt.value = true
@@ -1069,7 +1071,7 @@ const handleResetToDefault = async () => {
localUseCustomSystemPrompt.value = useCustom
savedUseCustomSystemPrompt = useCustom
- MessagePlugin.success('已恢复为默认 Prompt')
+ MessagePlugin.success(t('agentSettings.toasts.resetToDefault'))
confirmDialog.hide()
} catch (error) {
console.error('恢复默认 Prompt 失败:', error)
@@ -1125,7 +1127,7 @@ const handleSystemPromptChange = async (e?: FocusEvent) => {
await updateAgentConfig(config)
savedSystemPrompt = localSystemPrompt.value // 更新已保存的值
- MessagePlugin.success('系统 Prompt 已保存')
+ MessagePlugin.success(t('agentSettings.toasts.systemPromptSaved'))
} catch (error) {
console.error('保存系统 Prompt 失败:', error)
MessagePlugin.error(getErrorMessage(error))
@@ -1138,7 +1140,7 @@ watch(isAgentReady, (newValue, oldValue) => {
// 如果配置从"就绪"变为"未就绪",且 Agent 当前是启用状态,自动关闭
if (!newValue && oldValue && settingsStore.isAgentEnabled) {
settingsStore.toggleAgent(false)
- MessagePlugin.warning('Agent 配置不完整,已自动关闭 Agent 模式')
+ MessagePlugin.warning(t('agentSettings.toasts.autoDisabled'))
}
// 注意:配置从"未就绪"变为"就绪"时,不自动启用(让用户自己决定是否启用)
}
diff --git a/frontend/src/views/settings/ApiInfo.vue b/frontend/src/views/settings/ApiInfo.vue
index d93bf64f7..c9d885bc2 100644
--- a/frontend/src/views/settings/ApiInfo.vue
+++ b/frontend/src/views/settings/ApiInfo.vue
@@ -1,32 +1,32 @@
<template>
<div class="api-info">
<div class="section-header">
- <h2>API 信息</h2>
- <p class="section-description">查看和管理您的 API 密钥</p>
+ <h2>{{ $t('tenant.api.title') }}</h2>
+ <p class="section-description">{{ $t('tenant.api.description') }}</p>
</div>
- <!-- 加载状态 -->
+ <!-- Loading state -->
<div v-if="loading" class="loading-inline">
<t-loading size="small" />
- <span>正在加载信息...</span>
+ <span>{{ $t('tenant.loadingInfo') }}</span>
</div>
- <!-- 错误状态 -->
+ <!-- Error state -->
<div v-else-if="error" class="error-inline">
<t-alert theme="error" :message="error">
<template #operation>
- <t-button size="small" @click="loadInfo">重试</t-button>
+ <t-button size="small" @click="loadInfo">{{ $t('tenant.retry') }}</t-button>
</template>
</t-alert>
</div>
- <!-- 信息内容 -->
+ <!-- Content -->
<div v-else class="settings-group">
<!-- API Key -->
<div class="setting-row">
<div class="setting-info">
- <label>API Key</label>
- <p class="desc">用于 API 调用的密钥,请妥善保管</p>
+ <label>{{ $t('tenant.api.keyLabel') }}</label>
+ <p class="desc">{{ $t('tenant.api.keyDescription') }}</p>
</div>
<div class="setting-control">
<div class="api-key-control">
@@ -47,7 +47,7 @@
size="small"
variant="text"
@click="copyApiKey"
- title="复制 API Key"
+ :title="$t('tenant.api.copyTitle')"
>
<t-icon name="file-copy" />
</t-button>
@@ -55,61 +55,61 @@
</div>
</div>
- <!-- API 文档 -->
+ <!-- API docs -->
<div class="setting-row">
<div class="setting-info">
- <label>API 文档</label>
+ <label>{{ $t('tenant.api.docLabel') }}</label>
<p class="desc">
- 查看完整的 API 调用文档和示例,
+ {{ $t('tenant.api.docDescription') }}
<a @click="openApiDoc" class="doc-link">
- 打开文档
+ {{ $t('tenant.api.openDoc') }}
<t-icon name="link" class="link-icon" />
</a>
</p>
</div>
</div>
- <!-- 用户信息 -->
- <div class="info-section-title">用户信息</div>
+ <!-- User info -->
+ <div class="info-section-title">{{ $t('tenant.api.userSectionTitle') }}</div>
- <!-- 用户 ID -->
+ <!-- User ID -->
<div class="setting-row">
<div class="setting-info">
- <label>用户 ID</label>
- <p class="desc">您的唯一用户标识</p>
+ <label>{{ $t('tenant.api.userIdLabel') }}</label>
+ <p class="desc">{{ $t('tenant.api.userIdDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ userInfo?.id || '-' }}</span>
</div>
</div>
- <!-- 用户名 -->
+ <!-- Username -->
<div class="setting-row">
<div class="setting-info">
- <label>用户名</label>
- <p class="desc">您的登录用户名</p>
+ <label>{{ $t('tenant.api.usernameLabel') }}</label>
+ <p class="desc">{{ $t('tenant.api.usernameDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ userInfo?.username || '-' }}</span>
</div>
</div>
- <!-- 邮箱 -->
+ <!-- Email -->
<div class="setting-row">
<div class="setting-info">
- <label>邮箱</label>
- <p class="desc">您的注册邮箱地址</p>
+ <label>{{ $t('tenant.api.emailLabel') }}</label>
+ <p class="desc">{{ $t('tenant.api.emailDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ userInfo?.email || '-' }}</span>
</div>
</div>
- <!-- 用户创建时间 -->
+ <!-- Created at -->
<div class="setting-row">
<div class="setting-info">
- <label>注册时间</label>
- <p class="desc">账户创建的时间</p>
+ <label>{{ $t('tenant.api.createdAtLabel') }}</label>
+ <p class="desc">{{ $t('tenant.api.createdAtDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ formatDate(userInfo?.created_at) }}</span>
@@ -124,15 +124,18 @@
import { ref, computed, onMounted } from 'vue'
import { getCurrentUser, type TenantInfo, type UserInfo } from '@/api/auth'
import { MessagePlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
-// 响应式数据
+const { t, locale } = useI18n()
+
+// Reactive state
const tenantInfo = ref<TenantInfo | null>(null)
const userInfo = ref<UserInfo | null>(null)
const loading = ref(true)
const error = ref('')
const showApiKey = ref(false)
-// 计算属性
+// Computed
const displayApiKey = computed(() => {
if (!tenantInfo.value?.api_key) return ''
if (showApiKey.value) {
@@ -145,7 +148,7 @@ const displayApiKey = computed(() => {
return masked
})
-// 方法
+// Methods
const loadInfo = async () => {
try {
loading.value = true
@@ -153,14 +156,14 @@ const loadInfo = async () => {
const userResponse = await getCurrentUser()
- if (userResponse.success && userResponse.data) {
+ if ((userResponse as any).success && userResponse.data) {
userInfo.value = userResponse.data.user
tenantInfo.value = userResponse.data.tenant
} else {
- error.value = userResponse.message || '获取用户信息失败'
+ error.value = userResponse.message || t('tenant.messages.fetchFailed')
}
} catch (err: any) {
- error.value = err.message || '网络错误,请稍后重试'
+ error.value = err?.message || t('tenant.messages.networkError')
} finally {
loading.value = false
}
@@ -172,36 +175,37 @@ const openApiDoc = () => {
const copyApiKey = async () => {
if (!tenantInfo.value?.api_key) {
- MessagePlugin.warning('暂无 API Key')
+ MessagePlugin.warning(t('tenant.api.noKey'))
return
}
try {
await navigator.clipboard.writeText(tenantInfo.value.api_key)
- MessagePlugin.success('API Key 已复制到剪贴板')
+ MessagePlugin.success(t('tenant.api.copySuccess'))
} catch (err) {
- MessagePlugin.error('复制失败,请手动复制')
+ MessagePlugin.error(t('tenant.api.copyFailed'))
}
}
const formatDate = (dateStr: string | undefined) => {
- if (!dateStr) return '未知'
+ if (!dateStr) return t('tenant.unknown')
try {
const date = new Date(dateStr)
- return date.toLocaleString('zh-CN', {
+ const formatter = new Intl.DateTimeFormat(locale.value || 'zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
})
+ return formatter.format(date)
} catch {
- return '格式错误'
+ return t('tenant.formatError')
}
}
-// 生命周期
+// Lifecycle
onMounted(() => {
loadInfo()
})
diff --git a/frontend/src/views/settings/GeneralSettings.vue b/frontend/src/views/settings/GeneralSettings.vue
index 51cb38afc..e880a7098 100644
--- a/frontend/src/views/settings/GeneralSettings.vue
+++ b/frontend/src/views/settings/GeneralSettings.vue
@@ -1,26 +1,27 @@
<template>
<div class="general-settings">
<div class="section-header">
- <h2>常规设置</h2>
- <p class="section-description">配置语言、外观等基础选项</p>
+ <h2>{{ $t('general.title') }}</h2>
+ <p class="section-description">{{ $t('general.description') }}</p>
</div>
<div class="settings-group">
<!-- 语言选择 -->
<div class="setting-row">
<div class="setting-info">
- <label>语言</label>
- <p class="desc">选择界面显示语言</p>
+ <label>{{ $t('language.language') }}</label>
+ <p class="desc">{{ $t('language.languageDescription') }}</p>
</div>
<div class="setting-control">
<t-select
v-model="localLanguage"
- placeholder="选择语言"
+ :placeholder="$t('language.selectLanguage')"
@change="handleLanguageChange"
style="width: 280px;"
>
- <t-option value="zh-CN" label="中文">中文</t-option>
- <t-option value="en-US" label="English">English</t-option>
+ <t-option value="zh-CN" :label="$t('language.zhCN')">{{ $t('language.zhCN') }}</t-option>
+ <t-option value="en-US" :label="$t('language.enUS')">{{ $t('language.enUS') }}</t-option>
+ <t-option value="ru-RU" :label="$t('language.ruRU')">{{ $t('language.ruRU') }}</t-option>
</t-select>
</div>
</div>
@@ -29,8 +30,11 @@
</template>
<script setup lang="ts">
-import { ref, onMounted } from 'vue'
+import { ref, onMounted, computed } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
+
+const { t, locale } = useI18n()
// 本地状态
const localLanguage = ref('zh-CN')
@@ -38,40 +42,31 @@ const localTheme = ref('light')
// 初始化加载
onMounted(() => {
- // 从 localStorage 加载常规设置
- const savedSettings = localStorage.getItem('WeKnora_general_settings')
- if (savedSettings) {
- try {
- const parsed = JSON.parse(savedSettings)
- localLanguage.value = parsed.language || 'zh-CN'
- localTheme.value = parsed.theme || 'light'
- } catch (e) {
- console.error('加载常规设置失败:', e)
- }
+ // 从 localStorage 加载语言设置
+ const savedLocale = localStorage.getItem('locale')
+ if (savedLocale) {
+ localLanguage.value = savedLocale
+ locale.value = savedLocale
+ } else {
+ localLanguage.value = locale.value
}
})
-// 保存设置到 localStorage
-const saveSettings = () => {
- const settings = {
- language: localLanguage.value,
- theme: localTheme.value
- }
- localStorage.setItem('WeKnora_general_settings', JSON.stringify(settings))
-}
-
// 处理语言变化
const handleLanguageChange = () => {
- saveSettings()
- MessagePlugin.success('语言设置已保存')
- // TODO: 实际的语言切换逻辑可后续添加
-}
+ locale.value = localLanguage.value
+ localStorage.setItem('locale', localLanguage.value)
+ MessagePlugin.success(t('language.languageSaved'))
+ }
// 处理主题变化
const handleThemeChange = () => {
- saveSettings()
- MessagePlugin.success('主题设置已保存')
- // TODO: 实际的主题切换逻辑可后续添加
+ const settings = {
+ language: localLanguage.value,
+ theme: localTheme.value
+ }
+ localStorage.setItem('WeKnora_general_settings', JSON.stringify(settings))
+ MessagePlugin.success(t('common.success'))
}
</script>
diff --git a/frontend/src/views/settings/McpSettings.vue b/frontend/src/views/settings/McpSettings.vue
index 8555aaf51..d2a32136f 100644
--- a/frontend/src/views/settings/McpSettings.vue
+++ b/frontend/src/views/settings/McpSettings.vue
@@ -1,31 +1,31 @@
<template>
<div class="mcp-settings">
<div class="section-header">
- <h2>MCP 服务管理</h2>
+ <h2>{{ $t('mcpSettings.title') }}</h2>
<p class="section-description">
- 管理外部 MCP (Model Context Protocol) 服务,在 Agent 模式下调用外部工具和资源
+ {{ $t('mcpSettings.description') }}
</p>
</div>
<div v-if="loading" class="loading-container">
- <t-loading text="加载中..." />
+ <t-loading :text="$t('common.loading')" />
</div>
<div v-else class="services-container">
<div class="services-header">
<div class="header-info">
- <h3>已配置的服务</h3>
- <p>管理和测试 MCP 服务连接</p>
+ <h3>{{ $t('mcpSettings.configuredServices') }}</h3>
+ <p>{{ $t('mcpSettings.manageAndTest') }}</p>
</div>
<t-button size="small" theme="primary" @click="handleAdd">
<template #icon><t-icon name="add" /></template>
- 添加服务
+ {{ $t('mcpSettings.addService') }}
</t-button>
</div>
<div v-if="services.length === 0" class="empty-state">
- <t-empty description="暂无 MCP 服务">
- <t-button theme="primary" @click="handleAdd">添加第一个 MCP 服务</t-button>
+ <t-empty :description="$t('mcpSettings.empty')" >
+ <t-button theme="primary" @click="handleAdd">{{ $t('mcpSettings.addFirst') }}</t-button>
</t-empty>
</div>
@@ -89,6 +89,7 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
import {
listMCPServices,
updateMCPService,
@@ -100,6 +101,8 @@ import {
import McpServiceDialog from './components/McpServiceDialog.vue'
import McpTestResult from './components/McpTestResult.vue'
+const { t } = useI18n()
+
const services = ref<MCPService[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
@@ -116,7 +119,7 @@ const loadServices = async () => {
try {
services.value = await listMCPServices()
} catch (error) {
- MessagePlugin.error('加载 MCP 服务列表失败')
+ MessagePlugin.error(t('mcpSettings.toasts.loadFailed'))
console.error('Failed to load MCP services:', error)
} finally {
loading.value = false
@@ -150,11 +153,11 @@ const handleToggleEnabled = async (service: MCPService) => {
const originalState = service.enabled
try {
await updateMCPService(service.id, { enabled: service.enabled })
- MessagePlugin.success(`已${service.enabled ? '启用' : '禁用'} MCP 服务`)
+ MessagePlugin.success(service.enabled ? t('mcpSettings.toasts.enabled') : t('mcpSettings.toasts.disabled'))
} catch (error) {
// Revert on error
service.enabled = originalState
- MessagePlugin.error('更新 MCP 服务状态失败')
+ MessagePlugin.error(t('mcpSettings.toasts.updateStateFailed'))
console.error('Failed to update MCP service:', error)
}
}
@@ -168,7 +171,7 @@ const handleTest = async (service: MCPService) => {
// 显示测试开始提示
MessagePlugin.info({
- content: `正在测试 ${service.name}...`,
+ content: t('mcpSettings.toasts.testing', { name: service.name }),
duration: 0, // 不自动关闭
closeBtn: false
})
@@ -186,7 +189,7 @@ const handleTest = async (service: MCPService) => {
// 即使没有结果,也显示错误对话框
testResult.value = {
success: false,
- message: '测试失败:未收到服务器响应'
+ message: t('mcpSettings.toasts.noResponse')
}
testDialogVisible.value = true
return
@@ -203,7 +206,7 @@ const handleTest = async (service: MCPService) => {
MessagePlugin.closeAll()
// 显示错误信息
- const errorMessage = error?.response?.data?.error?.message || error?.message || '测试 MCP 服务失败'
+ const errorMessage = error?.response?.data?.error?.message || error?.message || t('mcpSettings.toasts.testFailed')
console.error('Failed to test MCP service:', error)
// 即使出错也显示结果对话框,显示错误信息
@@ -223,19 +226,19 @@ const handleDelete = async (service: MCPService) => {
if (!service || !service.id) return
const confirmDialog = DialogPlugin.confirm({
- header: '确认删除',
- body: `确定要删除 MCP 服务"${service.name || '未命名'}"吗?此操作无法撤销。`,
- confirmBtn: '删除',
- cancelBtn: '取消',
+ header: t('common.confirmDelete'),
+ body: t('mcpSettings.deleteConfirmBody', { name: service.name || t('mcpSettings.unnamed') }),
+ confirmBtn: t('common.delete'),
+ cancelBtn: t('common.cancel'),
theme: 'warning',
onConfirm: async () => {
try {
await deleteMCPService(service.id)
- MessagePlugin.success('MCP 服务已删除')
+ MessagePlugin.success(t('mcpSettings.toasts.deleted'))
confirmDialog.hide()
loadServices()
} catch (error) {
- MessagePlugin.error('删除 MCP 服务失败')
+ MessagePlugin.error(t('mcpSettings.toasts.deleteFailed'))
console.error('Failed to delete MCP service:', error)
}
}
@@ -246,15 +249,15 @@ const handleDelete = async (service: MCPService) => {
const getServiceOptions = (service: MCPService) => {
return [
{
- content: '测试连接',
+ content: t('mcpSettings.actions.test'),
value: `test-${service.id}`
},
{
- content: '编辑',
+ content: t('common.edit'),
value: `edit-${service.id}`
},
{
- content: '删除',
+ content: t('common.delete'),
value: `delete-${service.id}`,
theme: 'error'
}
diff --git a/frontend/src/views/settings/ModelSettings.vue b/frontend/src/views/settings/ModelSettings.vue
index ff635c7c1..4b00238f1 100644
--- a/frontend/src/views/settings/ModelSettings.vue
+++ b/frontend/src/views/settings/ModelSettings.vue
@@ -1,22 +1,22 @@
<template>
<div class="model-settings">
<div class="section-header">
- <h2>模型配置</h2>
- <p class="section-description">管理不同类型的 AI 模型,支持 Ollama 本地模型和远程 API</p>
+ <h2>{{ $t('modelSettings.title') }}</h2>
+ <p class="section-description">{{ $t('modelSettings.description') }}</p>
</div>
<!-- 对话模型 -->
<div class="model-category-section" data-model-type="chat">
<div class="category-header">
<div class="header-info">
- <h3>对话模型</h3>
- <p>配置用于对话的大语言模型</p>
+ <h3>{{ $t('modelSettings.chat.title') }}</h3>
+ <p>{{ $t('modelSettings.chat.desc') }}</p>
</div>
<t-button size="small" theme="primary" @click="openAddDialog('chat')">
<template #icon>
<t-icon name="add" />
</template>
- 添加模型
+ {{ $t('modelSettings.actions.addModel') }}
</t-button>
</div>
@@ -25,10 +25,10 @@
<div class="model-info">
<div class="model-name">
{{ model.name }}
- <t-tag v-if="model.isDefault" theme="success" size="small">默认</t-tag>
+ <t-tag v-if="model.isDefault" theme="success" size="small">{{ $t('common.default') }}</t-tag>
</div>
<div class="model-meta">
- <span class="source-tag">{{ model.source === 'local' ? 'Ollama' : 'Remote' }}</span>
+ <span class="source-tag">{{ model.source === 'local' ? 'Ollama' : $t('modelSettings.source.remote') }}</span>
<!-- <span class="model-id">{{ model.modelName }}</span> -->
</div>
</div>
@@ -47,9 +47,9 @@
</div>
</div>
<div v-else class="empty-state">
- <p class="empty-text">暂无对话模型</p>
+ <p class="empty-text">{{ $t('modelSettings.chat.empty') }}</p>
<t-button theme="default" variant="outline" size="small" @click="openAddDialog('chat')">
- 添加模型
+ {{ $t('modelSettings.actions.addModel') }}
</t-button>
</div>
</div>
@@ -58,14 +58,14 @@
<div class="model-category-section" data-model-type="embedding">
<div class="category-header">
<div class="header-info">
- <h3>Embedding 模型</h3>
- <p>配置用于文本向量化的嵌入模型</p>
+ <h3>{{ $t('modelSettings.embedding.title') }}</h3>
+ <p>{{ $t('modelSettings.embedding.desc') }}</p>
</div>
<t-button size="small" theme="primary" @click="openAddDialog('embedding')">
<template #icon>
<t-icon name="add" />
</template>
- 添加模型
+ {{ $t('modelSettings.actions.addModel') }}
</t-button>
</div>
@@ -74,12 +74,12 @@
<div class="model-info">
<div class="model-name">
{{ model.name }}
- <t-tag v-if="model.isDefault" theme="success" size="small">默认</t-tag>
+ <t-tag v-if="model.isDefault" theme="success" size="small">{{ $t('common.default') }}</t-tag>
</div>
<div class="model-meta">
- <span class="source-tag">{{ model.source === 'local' ? 'Ollama' : 'Remote' }}</span>
+ <span class="source-tag">{{ model.source === 'local' ? 'Ollama' : $t('modelSettings.source.remote') }}</span>
<!-- <span class="model-id">{{ model.modelName }}</span> -->
- <span v-if="model.dimension" class="dimension">维度: {{ model.dimension }}</span>
+ <span v-if="model.dimension" class="dimension">{{ $t('model.editor.dimensionLabel') }}: {{ model.dimension }}</span>
</div>
</div>
<div class="model-actions">
@@ -97,9 +97,9 @@
</div>
</div>
<div v-else class="empty-state">
- <p class="empty-text">暂无 Embedding 模型</p>
+ <p class="empty-text">{{ $t('modelSettings.embedding.empty') }}</p>
<t-button theme="default" variant="outline" size="small" @click="openAddDialog('embedding')">
- 添加模型
+ {{ $t('modelSettings.actions.addModel') }}
</t-button>
</div>
</div>
@@ -108,14 +108,14 @@
<div class="model-category-section" data-model-type="rerank">
<div class="category-header">
<div class="header-info">
- <h3>ReRank 模型</h3>
- <p>配置用于结果重排序的模型</p>
+ <h3>{{ $t('modelSettings.rerank.title') }}</h3>
+ <p>{{ $t('modelSettings.rerank.desc') }}</p>
</div>
<t-button size="small" theme="primary" @click="openAddDialog('rerank')">
<template #icon>
<t-icon name="add" />
</template>
- 添加模型
+ {{ $t('modelSettings.actions.addModel') }}
</t-button>
</div>
@@ -124,10 +124,10 @@
<div class="model-info">
<div class="model-name">
{{ model.name }}
- <t-tag v-if="model.isDefault" theme="success" size="small">默认</t-tag>
+ <t-tag v-if="model.isDefault" theme="success" size="small">{{ $t('common.default') }}</t-tag>
</div>
<div class="model-meta">
- <span class="source-tag">{{ model.source === 'local' ? 'Ollama' : 'Remote' }}</span>
+ <span class="source-tag">{{ model.source === 'local' ? 'Ollama' : $t('modelSettings.source.remote') }}</span>
<!-- <span class="model-id">{{ model.modelName }}</span> -->
</div>
</div>
@@ -146,9 +146,9 @@
</div>
</div>
<div v-else class="empty-state">
- <p class="empty-text">暂无 ReRank 模型</p>
+ <p class="empty-text">{{ $t('modelSettings.rerank.empty') }}</p>
<t-button theme="default" variant="outline" size="small" @click="openAddDialog('rerank')">
- 添加模型
+ {{ $t('modelSettings.actions.addModel') }}
</t-button>
</div>
</div>
@@ -157,14 +157,14 @@
<div class="model-category-section" data-model-type="vllm">
<div class="category-header">
<div class="header-info">
- <h3>VLLM 视觉模型</h3>
- <p>配置用于视觉理解和多模态的视觉语言模型</p>
+ <h3>{{ $t('modelSettings.vllm.title') }}</h3>
+ <p>{{ $t('modelSettings.vllm.desc') }}</p>
</div>
<t-button size="small" theme="primary" @click="openAddDialog('vllm')">
<template #icon>
<t-icon name="add" />
</template>
- 添加模型
+ {{ $t('modelSettings.actions.addModel') }}
</t-button>
</div>
@@ -173,10 +173,10 @@
<div class="model-info">
<div class="model-name">
{{ model.name }}
- <t-tag v-if="model.isDefault" theme="success" size="small">默认</t-tag>
+ <t-tag v-if="model.isDefault" theme="success" size="small">{{ $t('common.default') }}</t-tag>
</div>
<div class="model-meta">
- <span class="source-tag">{{ model.source === 'local' ? 'Ollama' : 'OpenAI兼容' }}</span>
+ <span class="source-tag">{{ model.source === 'local' ? 'Ollama' : $t('modelSettings.source.openaiCompatible') }}</span>
<!-- <span class="model-id">{{ model.modelName }}</span> -->
</div>
</div>
@@ -215,9 +215,12 @@
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
import ModelEditorDialog from '@/components/ModelEditorDialog.vue'
import { listModels, createModel, updateModel as updateModelAPI, deleteModel as deleteModelAPI, type ModelConfig } from '@/api/model'
+const { t } = useI18n()
+
const showDialog = ref(false)
const currentModelType = ref<'chat' | 'embedding' | 'rerank' | 'vllm'>('chat')
const editingModel = ref<any>(null)
@@ -337,19 +340,19 @@ const handleModelSave = async (modelData: any) => {
try {
// 字段校验
if (!modelData.modelName || !modelData.modelName.trim()) {
- MessagePlugin.warning('模型名称不能为空')
+ MessagePlugin.warning(t('modelSettings.toasts.nameRequired'))
return
}
if (modelData.modelName.trim().length > 100) {
- MessagePlugin.warning('模型名称不能超过100个字符')
+ MessagePlugin.warning(t('modelSettings.toasts.nameTooLong'))
return
}
// Remote 类型必须填写 baseUrl
if (modelData.source === 'remote') {
if (!modelData.baseUrl || !modelData.baseUrl.trim()) {
- MessagePlugin.warning('Remote API 类型必须填写 Base URL')
+ MessagePlugin.warning(t('modelSettings.toasts.baseUrlRequired'))
return
}
@@ -357,7 +360,7 @@ const handleModelSave = async (modelData: any) => {
try {
new URL(modelData.baseUrl.trim())
} catch {
- MessagePlugin.warning('Base URL 格式不正确,请输入有效的 URL')
+ MessagePlugin.warning(t('modelSettings.toasts.baseUrlInvalid'))
return
}
}
@@ -365,7 +368,7 @@ const handleModelSave = async (modelData: any) => {
// Embedding 模型必须填写维度
if (currentModelType.value === 'embedding') {
if (!modelData.dimension || modelData.dimension < 128 || modelData.dimension > 4096) {
- MessagePlugin.warning('Embedding 模型必须填写有效的向量维度(128-4096)')
+ MessagePlugin.warning(t('modelSettings.toasts.dimensionInvalid'))
return
}
}
@@ -392,18 +395,18 @@ const handleModelSave = async (modelData: any) => {
if (editingModel.value && editingModel.value.id) {
// 更新现有模型
await updateModelAPI(editingModel.value.id, apiModelData)
- MessagePlugin.success('模型已更新')
+ MessagePlugin.success(t('modelSettings.toasts.updated'))
} else {
// 添加新模型
await createModel(apiModelData)
- MessagePlugin.success('模型已添加')
+ MessagePlugin.success(t('modelSettings.toasts.added'))
}
// 重新加载模型列表
await loadModels()
} catch (error: any) {
console.error('保存模型失败:', error)
- MessagePlugin.error(error.message || '保存模型失败')
+ MessagePlugin.error(error.message || t('modelSettings.toasts.saveFailed'))
}
}
@@ -411,12 +414,12 @@ const handleModelSave = async (modelData: any) => {
const deleteModel = async (type: 'chat' | 'embedding' | 'rerank' | 'vllm', modelId: string) => {
try {
await deleteModelAPI(modelId)
- MessagePlugin.success('模型已删除')
+ MessagePlugin.success(t('modelSettings.toasts.deleted'))
// 重新加载模型列表
await loadModels()
} catch (error: any) {
console.error('删除模型失败:', error)
- MessagePlugin.error(error.message || '删除模型失败')
+ MessagePlugin.error(error.message || t('modelSettings.toasts.deleteFailed'))
}
}
@@ -425,12 +428,12 @@ const setDefault = async (type: 'chat' | 'embedding' | 'rerank' | 'vllm', modelI
try {
// 更新模型的 is_default 字段
await updateModelAPI(modelId, { is_default: true })
- MessagePlugin.success('已设为默认模型')
+ MessagePlugin.success(t('modelSettings.toasts.setDefault'))
// 重新加载模型列表
await loadModels()
} catch (error: any) {
console.error('设置默认模型失败:', error)
- MessagePlugin.error(error.message || '设置默认模型失败')
+ MessagePlugin.error(error.message || t('modelSettings.toasts.setDefaultFailed'))
}
}
@@ -441,20 +444,20 @@ const getModelOptions = (type: 'chat' | 'embedding' | 'rerank' | 'vllm', model:
// 如果不是默认模型,显示"设为默认"选项
if (!model.isDefault) {
options.push({
- content: '设为默认',
+ content: t('modelSettings.actions.setDefault'),
value: `set-default-${type}-${model.id}`
})
}
// 编辑选项
options.push({
- content: '编辑',
+ content: t('common.edit'),
value: `edit-${type}-${model.id}`
})
// 删除选项
options.push({
- content: '删除',
+ content: t('common.delete'),
value: `delete-${type}-${model.id}`,
theme: 'error'
})
@@ -472,7 +475,7 @@ const handleMenuAction = (data: { value: string }, type: 'chat' | 'embedding' |
editModel(type, model)
} else if (value.indexOf('delete-') === 0) {
// 使用确认对话框进行确认
- if (confirm('确定删除此模型吗?')) {
+ if (confirm(t('modelSettings.confirmDelete'))) {
deleteModel(type, model.id)
}
}
diff --git a/frontend/src/views/settings/OllamaSettings.vue b/frontend/src/views/settings/OllamaSettings.vue
index 4facf0a05..d04921feb 100644
--- a/frontend/src/views/settings/OllamaSettings.vue
+++ b/frontend/src/views/settings/OllamaSettings.vue
@@ -1,16 +1,16 @@
<template>
<div class="ollama-settings">
<div class="section-header">
- <h2>Ollama 配置</h2>
- <p class="section-description">管理本地 Ollama 服务,查看和下载模型</p>
+ <h2>{{ $t('ollamaSettings.title') }}</h2>
+ <p class="section-description">{{ $t('ollamaSettings.description') }}</p>
</div>
<div class="settings-group">
<!-- Ollama 服务状态 -->
<div class="setting-row">
<div class="setting-info">
- <label>Ollama 服务状态</label>
- <p class="desc">自动检测本地 Ollama 服务是否可用。如果服务未运行或地址配置错误,将显示"不可用"状态</p>
+ <label>{{ $t('ollamaSettings.status.label') }}</label>
+ <p class="desc">{{ $t('ollamaSettings.status.desc') }}</p>
</div>
<div class="setting-control">
<div class="status-display">
@@ -20,7 +20,7 @@
variant="light"
>
<t-icon name="loading" class="status-icon spinning" />
- 检测中
+ {{ $t('ollamaSettings.status.testing') }}
</t-tag>
<t-tag
v-else-if="connectionStatus === true"
@@ -28,7 +28,7 @@
variant="light"
>
<t-icon name="check-circle-filled" />
- 可用
+ {{ $t('ollamaSettings.status.available') }}
</t-tag>
<t-tag
v-else-if="connectionStatus === false"
@@ -36,7 +36,7 @@
variant="light"
>
<t-icon name="close-circle-filled" />
- 不可用
+ {{ $t('ollamaSettings.status.unavailable') }}
</t-tag>
<t-tag
v-else
@@ -44,7 +44,7 @@
variant="light"
>
<t-icon name="help-circle" />
- 未检测
+ {{ $t('ollamaSettings.status.untested') }}
</t-tag>
<t-button
size="small"
@@ -53,7 +53,7 @@
@click="testConnection"
>
<t-icon name="refresh" />
- 重新检测
+ {{ $t('ollamaSettings.status.retest') }}
</t-button>
</div>
</div>
@@ -62,14 +62,14 @@
<!-- Ollama 服务地址 -->
<div class="setting-row">
<div class="setting-info">
- <label>服务地址</label>
- <p class="desc">本地 Ollama 服务的 API 地址,由系统自动检测。如需修改,请在 .env 配置文件中设置</p>
+ <label>{{ $t('ollamaSettings.address.label') }}</label>
+ <p class="desc">{{ $t('ollamaSettings.address.desc') }}</p>
</div>
<div class="setting-control">
<div class="url-control-group">
<t-input
v-model="localBaseUrl"
- placeholder="http://localhost:11434"
+ :placeholder="$t('ollamaSettings.address.placeholder')"
disabled
style="flex: 1;"
/>
@@ -77,7 +77,7 @@
<t-alert
v-if="connectionStatus === false"
theme="warning"
- message="连接失败,请检查 Ollama 是否运行或服务地址是否正确"
+ :message="$t('ollamaSettings.address.failed')"
style="margin-top: 8px;"
/>
</div>
@@ -89,11 +89,11 @@
<div v-if="connectionStatus === true" class="model-category-section">
<div class="category-header">
<div class="header-info">
- <h3>下载新模型</h3>
+ <h3>{{ $t('ollamaSettings.download.title') }}</h3>
<p>
- 输入模型名称下载,
+ {{ $t('ollamaSettings.download.descPrefix') }}
<a href="https://ollama.com/search" target="_blank" rel="noopener noreferrer" class="model-link">
- 浏览 Ollama 模型库
+ {{ $t('ollamaSettings.download.browse') }}
<t-icon name="link" class="link-icon" />
</a>
</p>
@@ -104,7 +104,7 @@
<div class="input-group">
<t-input
v-model="downloadModelName"
- placeholder="如:qwen2.5:0.5b"
+ :placeholder="$t('ollamaSettings.download.placeholder')"
style="flex: 1;"
/>
<t-button
@@ -114,13 +114,13 @@
:disabled="!downloadModelName.trim()"
@click="downloadModel"
>
- 下载
+ {{ $t('ollamaSettings.download.download') }}
</t-button>
</div>
<div v-if="downloadProgress > 0" class="download-progress">
<div class="progress-info">
- <span>正在下载: {{ downloadModelName }}</span>
+ <span>{{ $t('ollamaSettings.download.downloading', { name: downloadModelName }) }}</span>
<span>{{ downloadProgress.toFixed(2) }}%</span>
</div>
<t-progress :percentage="downloadProgress" size="small" />
@@ -132,8 +132,8 @@
<div v-if="connectionStatus === true" class="model-category-section">
<div class="category-header">
<div class="header-info">
- <h3>已下载的模型</h3>
- <p>已安装在 Ollama 中的模型列表</p>
+ <h3>{{ $t('ollamaSettings.installed.title') }}</h3>
+ <p>{{ $t('ollamaSettings.installed.desc') }}</p>
</div>
<t-button
size="small"
@@ -141,13 +141,13 @@
:loading="loadingModels"
@click="refreshModels"
>
- <t-icon name="refresh" />刷新
+ <t-icon name="refresh" />{{ $t('common.refresh') }}
</t-button>
</div>
<div v-if="loadingModels" class="loading-state">
<t-loading size="small" />
- <span>加载中...</span>
+ <span>{{ $t('common.loading') }}</span>
</div>
<div v-else-if="downloadedModels.length > 0" class="model-list-container">
<div v-for="model in downloadedModels" :key="model.name" class="model-card">
@@ -161,7 +161,7 @@
</div>
</div>
<div v-else class="empty-state">
- <p class="empty-text">暂无已下载的模型</p>
+ <p class="empty-text">{{ $t('ollamaSettings.installed.empty') }}</p>
</div>
</div>
</div>
@@ -171,9 +171,11 @@
import { ref, onMounted } from 'vue'
import { useSettingsStore } from '@/stores/settings'
import { MessagePlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
import { checkOllamaStatus, listOllamaModels, downloadOllamaModel, getDownloadProgress, type OllamaModelInfo } from '@/api/initialization'
const settingsStore = useSettingsStore()
+const { t } = useI18n()
const localBaseUrl = ref(settingsStore.settings.ollamaConfig?.baseUrl ?? '')
@@ -206,14 +208,14 @@ const testConnection = async () => {
connectionStatus.value = result.available
if (connectionStatus.value) {
- MessagePlugin.success('连接成功')
+ MessagePlugin.success(t('ollamaSettings.toasts.connected'))
refreshModels()
} else {
- MessagePlugin.error(result.error || '连接失败,请检查 Ollama 是否运行')
+ MessagePlugin.error(result.error || t('ollamaSettings.toasts.connectFailed'))
}
} catch (error: any) {
connectionStatus.value = false
- MessagePlugin.error(error.message || '连接失败')
+ MessagePlugin.error(error.message || t('ollamaSettings.toasts.connectFailed'))
} finally {
testing.value = false
}
@@ -229,7 +231,7 @@ const refreshModels = async () => {
downloadedModels.value = models
} catch (error: any) {
console.error('获取模型列表失败:', error)
- MessagePlugin.error(error.message || '获取模型列表失败')
+ MessagePlugin.error(error.message || t('ollamaSettings.toasts.listFailed'))
} finally {
loadingModels.value = false
}
@@ -275,13 +277,13 @@ const downloadModel = async () => {
const result = await downloadOllamaModel(downloadModelName.value)
if (result.status === 'failed') {
- MessagePlugin.error('下载失败,请稍后重试')
+ MessagePlugin.error(t('ollamaSettings.toasts.downloadFailed'))
downloading.value = false
downloadProgress.value = 0
return
}
- MessagePlugin.success(`已开始下载模型 ${downloadModelName.value}`)
+ MessagePlugin.success(t('ollamaSettings.toasts.downloadStarted', { name: downloadModelName.value }))
// 查询下载进度
const taskId = result.taskId
@@ -292,27 +294,27 @@ const downloadModel = async () => {
if (task.status === 'completed') {
clearInterval(progressInterval)
- MessagePlugin.success(`模型 ${downloadModelName.value} 下载完成`)
+ MessagePlugin.success(t('ollamaSettings.toasts.downloadCompleted', { name: downloadModelName.value }))
downloadModelName.value = ''
downloadProgress.value = 0
downloading.value = false
refreshModels()
} else if (task.status === 'failed') {
clearInterval(progressInterval)
- MessagePlugin.error(task.message || '下载失败')
+ MessagePlugin.error(task.message || t('ollamaSettings.toasts.downloadFailed'))
downloading.value = false
downloadProgress.value = 0
}
} catch (error) {
clearInterval(progressInterval)
- MessagePlugin.error('查询下载进度失败')
+ MessagePlugin.error(t('ollamaSettings.toasts.progressFailed'))
downloading.value = false
downloadProgress.value = 0
}
}, 1000)
} catch (error: any) {
console.error('下载失败:', error)
- MessagePlugin.error(error.message || '下载失败')
+ MessagePlugin.error(error.message || t('ollamaSettings.toasts.downloadFailed'))
downloading.value = false
downloadProgress.value = 0
}
diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vue
index 0db9a0a5e..0dc0a27ed 100644
--- a/frontend/src/views/settings/Settings.vue
+++ b/frontend/src/views/settings/Settings.vue
@@ -4,7 +4,7 @@
<div v-if="visible" class="settings-overlay">
<div class="settings-modal">
<!-- 关闭按钮 -->
- <button class="close-btn" @click="handleClose" aria-label="关闭设置">
+ <button class="close-btn" @click="handleClose" :aria-label="$t('general.close')">
<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
<path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>
@@ -14,7 +14,7 @@
<!-- 左侧导航 -->
<div class="settings-sidebar">
<div class="sidebar-header">
- <h2 class="sidebar-title">设置</h2>
+ <h2 class="sidebar-title">{{ $t('general.settings') }}</h2>
</div>
<div class="settings-nav">
<template v-for="(item, index) in navItems" :key="index">
@@ -131,6 +131,7 @@
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUIStore } from '@/stores/ui'
+import { useI18n } from 'vue-i18n'
import AgentSettings from './AgentSettings.vue'
import SystemInfo from './SystemInfo.vue'
import TenantInfo from './TenantInfo.vue'
@@ -144,32 +145,33 @@ import WebSearchSettings from './WebSearchSettings.vue'
const route = useRoute()
const router = useRouter()
const uiStore = useUIStore()
+const { t } = useI18n()
const currentSection = ref<string>('general')
const currentSubSection = ref<string>('')
const expandedMenus = ref<string[]>([])
-const navItems = [
- { key: 'general', icon: 'setting', label: '常规' },
+const navItems = computed(() => [
+ { key: 'general', icon: 'setting', label: t('general.title') },
{
key: 'models',
icon: 'control-platform',
- label: '模型配置',
+ label: t('settings.modelConfig'),
children: [
- { key: 'chat', label: '对话模型' },
- { key: 'embedding', label: 'Embedding' },
- { key: 'rerank', label: 'ReRank' },
- { key: 'vllm', label: 'VLLM' }
+ { key: 'chat', label: t('model.llmModel') },
+ { key: 'embedding', label: t('model.embeddingModel') },
+ { key: 'rerank', label: t('model.rerankModel') },
+ { key: 'vllm', label: t('model.vlmModel') }
]
},
{ key: 'ollama', icon: 'server', label: 'Ollama' },
- { key: 'agent', icon: 'chat', label: 'Agent 配置' },
- { key: 'websearch', icon: 'search', label: '网络搜索' },
- { key: 'mcp', icon: 'link', label: 'MCP 服务' },
- { key: 'system', icon: 'info-circle', label: '系统信息' },
- { key: 'tenant', icon: 'user-circle', label: '租户信息' },
- { key: 'api', icon: 'secured', label: 'API 信息' }
-]
+ { key: 'agent', icon: 'chat', label: t('settings.agentConfig') },
+ { key: 'websearch', icon: 'search', label: t('settings.webSearchConfig') },
+{ key: 'mcp', icon: 'tools', label: t('settings.mcpService') },
+ { key: 'system', icon: 'info-circle', label: t('settings.systemSettings') },
+ { key: 'tenant', icon: 'user-circle', label: t('settings.tenantInfo') },
+ { key: 'api', icon: 'secured', label: t('settings.apiInfo') }
+])
// 导航项点击处理
const handleNavClick = (item: any) => {
diff --git a/frontend/src/views/settings/SystemInfo.vue b/frontend/src/views/settings/SystemInfo.vue
index 424780b28..606c41e8e 100644
--- a/frontend/src/views/settings/SystemInfo.vue
+++ b/frontend/src/views/settings/SystemInfo.vue
@@ -1,36 +1,36 @@
<template>
<div class="system-info">
<div class="section-header">
- <h2>系统信息</h2>
- <p class="section-description">查看系统版本信息和用户账户配置</p>
+ <h2>{{ $t('system.title') }}</h2>
+ <p class="section-description">{{ $t('system.sectionDescription') }}</p>
</div>
- <!-- 加载状态 -->
+ <!-- Loading state -->
<div v-if="loading" class="loading-inline">
<t-loading size="small" />
- <span>正在加载信息...</span>
+ <span>{{ $t('system.loadingInfo') }}</span>
</div>
- <!-- 错误状态 -->
+ <!-- Error state -->
<div v-else-if="error" class="error-inline">
<t-alert theme="error" :message="error">
<template #operation>
- <t-button size="small" @click="loadInfo">重试</t-button>
+ <t-button size="small" @click="loadInfo">{{ $t('system.retry') }}</t-button>
</template>
</t-alert>
</div>
- <!-- 信息内容 -->
+ <!-- Content -->
<div v-else class="settings-group">
- <!-- 系统版本 -->
+ <!-- System version -->
<div class="setting-row">
<div class="setting-info">
- <label>系统版本</label>
- <p class="desc">当前系统的版本号</p>
+ <label>{{ $t('system.versionLabel') }}</label>
+ <p class="desc">{{ $t('system.versionDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">
- {{ systemInfo?.version || '未知' }}
+ {{ systemInfo?.version || $t('system.unknown') }}
<span v-if="systemInfo?.commit_id" class="commit-info">
({{ systemInfo.commit_id }})
</span>
@@ -38,22 +38,22 @@
</div>
</div>
- <!-- 构建时间 -->
+ <!-- Build time -->
<div v-if="systemInfo?.build_time" class="setting-row">
<div class="setting-info">
- <label>构建时间</label>
- <p class="desc">系统构建的时间</p>
+ <label>{{ $t('system.buildTimeLabel') }}</label>
+ <p class="desc">{{ $t('system.buildTimeDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ systemInfo.build_time }}</span>
</div>
</div>
- <!-- Go版本 -->
+ <!-- Go version -->
<div v-if="systemInfo?.go_version" class="setting-row">
<div class="setting-info">
- <label>Go 版本</label>
- <p class="desc">后端使用的 Go 语言版本</p>
+ <label>{{ $t('system.goVersionLabel') }}</label>
+ <p class="desc">{{ $t('system.goVersionDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ systemInfo.go_version }}</span>
@@ -67,13 +67,16 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getSystemInfo, type SystemInfo } from '@/api/system'
+import { useI18n } from 'vue-i18n'
-// 响应式数据
+const { t } = useI18n()
+
+// Reactive state
const systemInfo = ref<SystemInfo | null>(null)
const loading = ref(true)
const error = ref('')
-// 方法
+// Methods
const loadInfo = async () => {
try {
loading.value = true
@@ -84,16 +87,16 @@ const loadInfo = async () => {
if (systemResponse.data) {
systemInfo.value = systemResponse.data
} else {
- error.value = '获取系统信息失败'
+ error.value = t('system.messages.fetchFailed')
}
} catch (err: any) {
- error.value = err.message || '网络错误,请稍后重试'
+ error.value = err?.message || t('system.messages.networkError')
} finally {
loading.value = false
}
}
-// 生命周期
+// Lifecycle
onMounted(() => {
loadInfo()
})
diff --git a/frontend/src/views/settings/TenantInfo.vue b/frontend/src/views/settings/TenantInfo.vue
index 80276dcdb..26777cdc7 100644
--- a/frontend/src/views/settings/TenantInfo.vue
+++ b/frontend/src/views/settings/TenantInfo.vue
@@ -1,76 +1,76 @@
<template>
<div class="tenant-info">
<div class="section-header">
- <h2>租户信息</h2>
- <p class="section-description">查看租户的详细配置信息</p>
+ <h2>{{ $t('tenant.title') }}</h2>
+ <p class="section-description">{{ $t('tenant.sectionDescription') }}</p>
</div>
- <!-- 加载状态 -->
+ <!-- Loading state -->
<div v-if="loading" class="loading-inline">
<t-loading size="small" />
- <span>正在加载信息...</span>
+ <span>{{ $t('tenant.loadingInfo') }}</span>
</div>
- <!-- 错误状态 -->
+ <!-- Error state -->
<div v-else-if="error" class="error-inline">
<t-alert theme="error" :message="error">
<template #operation>
- <t-button size="small" @click="loadInfo">重试</t-button>
+ <t-button size="small" @click="loadInfo">{{ $t('tenant.retry') }}</t-button>
</template>
</t-alert>
</div>
- <!-- 信息内容 -->
+ <!-- Content -->
<div v-else class="settings-group">
- <!-- 租户 ID -->
+ <!-- Tenant ID -->
<div class="setting-row">
<div class="setting-info">
- <label>租户 ID</label>
- <p class="desc">您所属租户的唯一标识</p>
+ <label>{{ $t('tenant.details.idLabel') }}</label>
+ <p class="desc">{{ $t('tenant.details.idDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ tenantInfo?.id || '-' }}</span>
</div>
</div>
- <!-- 租户名称 -->
+ <!-- Tenant name -->
<div class="setting-row">
<div class="setting-info">
- <label>租户名称</label>
- <p class="desc">您所属的租户名称</p>
+ <label>{{ $t('tenant.details.nameLabel') }}</label>
+ <p class="desc">{{ $t('tenant.details.nameDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ tenantInfo?.name || '-' }}</span>
</div>
</div>
- <!-- 租户描述 -->
+ <!-- Tenant description -->
<div v-if="tenantInfo?.description" class="setting-row">
<div class="setting-info">
- <label>租户描述</label>
- <p class="desc">租户的详细描述信息</p>
+ <label>{{ $t('tenant.details.descriptionLabel') }}</label>
+ <p class="desc">{{ $t('tenant.details.descriptionDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ tenantInfo.description }}</span>
</div>
</div>
- <!-- 租户业务 -->
+ <!-- Tenant business -->
<div v-if="tenantInfo?.business" class="setting-row">
<div class="setting-info">
- <label>租户业务</label>
- <p class="desc">租户所属的业务类型</p>
+ <label>{{ $t('tenant.details.businessLabel') }}</label>
+ <p class="desc">{{ $t('tenant.details.businessDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ tenantInfo.business }}</span>
</div>
</div>
- <!-- 租户状态 -->
+ <!-- Tenant status -->
<div class="setting-row">
<div class="setting-info">
- <label>租户状态</label>
- <p class="desc">租户当前的运行状态</p>
+ <label>{{ $t('tenant.details.statusLabel') }}</label>
+ <p class="desc">{{ $t('tenant.details.statusDescription') }}</p>
</div>
<div class="setting-control">
<t-tag
@@ -83,44 +83,44 @@
</div>
</div>
- <!-- 租户创建时间 -->
+ <!-- Tenant creation time -->
<div class="setting-row">
<div class="setting-info">
- <label>租户创建时间</label>
- <p class="desc">租户创建的时间</p>
+ <label>{{ $t('tenant.details.createdAtLabel') }}</label>
+ <p class="desc">{{ $t('tenant.details.createdAtDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ formatDate(tenantInfo?.created_at) }}</span>
</div>
</div>
- <!-- 存储配额 -->
+ <!-- Storage quota -->
<div v-if="tenantInfo?.storage_quota !== undefined" class="setting-row">
<div class="setting-info">
- <label>存储配额</label>
- <p class="desc">租户的总存储空间配额</p>
+ <label>{{ $t('tenant.storage.quotaLabel') }}</label>
+ <p class="desc">{{ $t('tenant.storage.quotaDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ formatBytes(tenantInfo.storage_quota) }}</span>
</div>
</div>
- <!-- 已使用存储 -->
+ <!-- Used storage -->
<div v-if="tenantInfo?.storage_quota !== undefined" class="setting-row">
<div class="setting-info">
- <label>已使用存储</label>
- <p class="desc">已经使用的存储空间</p>
+ <label>{{ $t('tenant.storage.usedLabel') }}</label>
+ <p class="desc">{{ $t('tenant.storage.usedDescription') }}</p>
</div>
<div class="setting-control">
<span class="info-value">{{ formatBytes(tenantInfo.storage_used || 0) }}</span>
</div>
</div>
- <!-- 存储使用率 -->
+ <!-- Storage usage -->
<div v-if="tenantInfo?.storage_quota !== undefined" class="setting-row">
<div class="setting-info">
- <label>存储使用率</label>
- <p class="desc">存储空间的使用百分比</p>
+ <label>{{ $t('tenant.storage.usageLabel') }}</label>
+ <p class="desc">{{ $t('tenant.storage.usageDescription') }}</p>
</div>
<div class="setting-control">
<div class="usage-control">
@@ -143,13 +143,16 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getCurrentUser, type TenantInfo } from '@/api/auth'
+import { useI18n } from 'vue-i18n'
-// 响应式数据
+const { t, locale } = useI18n()
+
+// Reactive state
const tenantInfo = ref<TenantInfo | null>(null)
const loading = ref(true)
const error = ref('')
-// 方法
+// Methods
const loadInfo = async () => {
try {
loading.value = true
@@ -157,13 +160,13 @@ const loadInfo = async () => {
const userResponse = await getCurrentUser()
- if (userResponse.success && userResponse.data) {
+ if ((userResponse as any).success && userResponse.data) {
tenantInfo.value = userResponse.data.tenant
} else {
- error.value = userResponse.message || '获取租户信息失败'
+ error.value = userResponse.message || t('tenant.messages.fetchFailed')
}
} catch (err: any) {
- error.value = err.message || '网络错误,请稍后重试'
+ error.value = err?.message || t('tenant.messages.networkError')
} finally {
loading.value = false
}
@@ -172,13 +175,13 @@ const loadInfo = async () => {
const getStatusText = (status: string | undefined) => {
switch (status) {
case 'active':
- return '活跃'
+ return t('tenant.statusActive')
case 'inactive':
- return '未激活'
+ return t('tenant.statusInactive')
case 'suspended':
- return '已暂停'
+ return t('tenant.statusSuspended')
default:
- return '未知'
+ return t('tenant.statusUnknown')
}
}
@@ -196,19 +199,20 @@ const getStatusTheme = (status: string | undefined) => {
}
const formatDate = (dateStr: string | undefined) => {
- if (!dateStr) return '未知'
+ if (!dateStr) return t('tenant.unknown')
try {
const date = new Date(dateStr)
- return date.toLocaleString('zh-CN', {
+ const formatter = new Intl.DateTimeFormat(locale.value || 'zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
})
+ return formatter.format(date)
} catch {
- return '格式错误'
+ return t('tenant.formatError')
}
}
@@ -232,7 +236,7 @@ const getUsagePercentage = () => {
return Math.min(Math.round(percentage * 100) / 100, 100)
}
-// 生命周期
+// Lifecycle
onMounted(() => {
loadInfo()
})
diff --git a/frontend/src/views/settings/WebSearchSettings.vue b/frontend/src/views/settings/WebSearchSettings.vue
index c3c3a1bf8..75e188c90 100644
--- a/frontend/src/views/settings/WebSearchSettings.vue
+++ b/frontend/src/views/settings/WebSearchSettings.vue
@@ -1,23 +1,23 @@
<template>
<div class="websearch-settings">
<div class="section-header">
- <h2>网络搜索配置</h2>
- <p class="section-description">配置网络搜索功能,在回答问题时可以从互联网获取实时信息补充知识库内容</p>
+ <h2>{{ t('webSearchSettings.title') }}</h2>
+ <p class="section-description">{{ t('webSearchSettings.description') }}</p>
</div>
<div class="settings-group">
<!-- 搜索引擎提供商 -->
<div class="setting-row">
<div class="setting-info">
- <label>搜索引擎提供商</label>
- <p class="desc">选择用于网络搜索的搜索引擎服务</p>
+ <label>{{ t('webSearchSettings.providerLabel') }}</label>
+ <p class="desc">{{ t('webSearchSettings.providerDescription') }}</p>
</div>
<div class="setting-control">
<t-select
v-model="localProvider"
:loading="loadingProviders"
filterable
- placeholder="选择搜索引擎..."
+ :placeholder="t('webSearchSettings.providerPlaceholder')"
@change="handleProviderChange"
@focus="loadProviders"
style="width: 280px;"
@@ -41,14 +41,14 @@
<!-- API 密钥 -->
<div v-if="selectedProvider && selectedProvider.requires_api_key" class="setting-row">
<div class="setting-info">
- <label>API 密钥</label>
- <p class="desc">输入所选搜索引擎的 API 密钥</p>
+ <label>{{ t('webSearchSettings.apiKeyLabel') }}</label>
+ <p class="desc">{{ t('webSearchSettings.apiKeyDescription') }}</p>
</div>
<div class="setting-control">
<t-input
v-model="localAPIKey"
type="password"
- placeholder="请输入 API 密钥"
+ :placeholder="t('webSearchSettings.apiKeyPlaceholder')"
@change="handleAPIKeyChange"
style="width: 400px;"
:show-password="true"
@@ -59,8 +59,8 @@
<!-- 最大结果数 -->
<div class="setting-row">
<div class="setting-info">
- <label>最大结果数</label>
- <p class="desc">每次搜索返回的最大结果数量(1-50)</p>
+ <label>{{ t('webSearchSettings.maxResultsLabel') }}</label>
+ <p class="desc">{{ t('webSearchSettings.maxResultsDescription') }}</p>
</div>
<div class="setting-control">
<div class="slider-with-value">
@@ -81,8 +81,8 @@
<!-- 包含日期 -->
<div class="setting-row">
<div class="setting-info">
- <label>包含发布日期</label>
- <p class="desc">在搜索结果中包含内容的发布日期信息</p>
+ <label>{{ t('webSearchSettings.includeDateLabel') }}</label>
+ <p class="desc">{{ t('webSearchSettings.includeDateDescription') }}</p>
</div>
<div class="setting-control">
<t-switch
@@ -95,8 +95,8 @@
<!-- 压缩方法 -->
<div class="setting-row">
<div class="setting-info">
- <label>压缩方法</label>
- <p class="desc">对搜索结果内容的压缩处理方法</p>
+ <label>{{ t('webSearchSettings.compressionLabel') }}</label>
+ <p class="desc">{{ t('webSearchSettings.compressionDescription') }}</p>
</div>
<div class="setting-control">
<t-select
@@ -104,8 +104,12 @@
@change="handleCompressionMethodChange"
style="width: 280px;"
>
- <t-option value="none" label="无压缩">无压缩</t-option>
- <t-option value="llm_summary" label="LLM 摘要">LLM 摘要</t-option>
+ <t-option value="none" :label="t('webSearchSettings.compressionNone')">
+ {{ t('webSearchSettings.compressionNone') }}
+ </t-option>
+ <t-option value="llm_summary" :label="t('webSearchSettings.compressionSummary')">
+ {{ t('webSearchSettings.compressionSummary') }}
+ </t-option>
</t-select>
</div>
</div>
@@ -113,13 +117,13 @@
<!-- 黑名单 -->
<div class="setting-row vertical">
<div class="setting-info">
- <label>URL 黑名单</label>
- <p class="desc">排除特定域名或 URL 的搜索结果,每行一个。支持通配符(*)和正则表达式(以/开头和结尾)</p>
+ <label>{{ t('webSearchSettings.blacklistLabel') }}</label>
+ <p class="desc">{{ t('webSearchSettings.blacklistDescription') }}</p>
</div>
<div class="setting-control">
<t-textarea
v-model="localBlacklistText"
- placeholder="例如:&#10;*://*.example.com/*&#10;/example\.(net|org)/"
+ :placeholder="t('webSearchSettings.blacklistPlaceholder')"
:autosize="{ minRows: 4, maxRows: 8 }"
@change="handleBlacklistChange"
style="width: 500px;"
@@ -133,8 +137,11 @@
<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
import { getWebSearchProviders, getTenantWebSearchConfig, updateTenantWebSearchConfig, type WebSearchProviderConfig, type WebSearchConfig } from '@/api/web-search'
+const { t } = useI18n()
+
// 本地状态
const loadingProviders = ref(false)
const providers = ref<WebSearchProviderConfig[]>([])
@@ -167,7 +174,8 @@ const loadProviders = async () => {
}
} catch (error: any) {
console.error('Failed to load web search providers:', error)
- MessagePlugin.error('加载搜索引擎列表失败: ' + (error.message || '未知错误'))
+ const errorMessage = error?.message || t('webSearchSettings.errors.unknown')
+ MessagePlugin.error(t('webSearchSettings.toasts.loadProvidersFailed', { message: errorMessage }))
} finally {
loadingProviders.value = false
}
@@ -314,10 +322,11 @@ const saveConfig = async () => {
blacklist: [...config.blacklist]
}
- MessagePlugin.success('网络搜索配置已保存')
+ MessagePlugin.success(t('webSearchSettings.toasts.saveSuccess'))
} catch (error: any) {
console.error('Failed to save web search config:', error)
- MessagePlugin.error('保存配置失败: ' + (error.message || '未知错误'))
+ const errorMessage = error?.message || t('webSearchSettings.errors.unknown')
+ MessagePlugin.error(t('webSearchSettings.toasts.saveFailed', { message: errorMessage }))
throw error
}
}
diff --git a/frontend/src/views/settings/components/McpServiceDialog.vue b/frontend/src/views/settings/components/McpServiceDialog.vue
index 0cf1a8a02..95036992b 100644
--- a/frontend/src/views/settings/components/McpServiceDialog.vue
+++ b/frontend/src/views/settings/components/McpServiceDialog.vue
@@ -1,11 +1,11 @@
<template>
<t-dialog
v-model:visible="dialogVisible"
- :header="mode === 'add' ? '添加 MCP 服务' : '编辑 MCP 服务'"
+ :header="mode === 'add' ? t('mcpServiceDialog.addTitle') : t('mcpServiceDialog.editTitle')"
width="700px"
:on-confirm="handleSubmit"
:on-cancel="handleClose"
- :confirm-btn="{ content: '保存', loading: submitting }"
+ :confirm-btn="{ content: t('common.save'), loading: submitting }"
>
<t-form
ref="formRef"
@@ -13,45 +13,45 @@
:rules="rules"
label-width="120px"
>
- <t-form-item label="服务名称" name="name">
- <t-input v-model="formData.name" placeholder="请输入服务名称" />
+ <t-form-item :label="t('mcpServiceDialog.name')" name="name">
+ <t-input v-model="formData.name" :placeholder="t('mcpServiceDialog.namePlaceholder')" />
</t-form-item>
- <t-form-item label="描述" name="description">
+ <t-form-item :label="t('mcpServiceDialog.description')" name="description">
<t-textarea
v-model="formData.description"
:autosize="{ minRows: 3, maxRows: 5 }"
- placeholder="请输入服务描述"
+ :placeholder="t('mcpServiceDialog.descriptionPlaceholder')"
/>
</t-form-item>
- <t-form-item label="传输类型" name="transport_type">
+ <t-form-item :label="t('mcpServiceDialog.transportType')" name="transport_type">
<t-radio-group v-model="formData.transport_type">
- <t-radio value="sse">SSE (Server-Sent Events)</t-radio>
- <t-radio value="http-streamable">HTTP Streamable</t-radio>
- <t-radio value="stdio">Stdio</t-radio>
+ <t-radio value="sse">{{ t('mcpServiceDialog.transport.sse') }}</t-radio>
+ <t-radio value="http-streamable">{{ t('mcpServiceDialog.transport.httpStreamable') }}</t-radio>
+ <t-radio value="stdio">{{ t('mcpServiceDialog.transport.stdio') }}</t-radio>
</t-radio-group>
</t-form-item>
<!-- URL for SSE/HTTP Streamable -->
<t-form-item
v-if="formData.transport_type !== 'stdio'"
- label="服务 URL"
+ :label="t('mcpServiceDialog.serviceUrl')"
name="url"
>
- <t-input v-model="formData.url" placeholder="https://example.com/mcp" />
+ <t-input v-model="formData.url" :placeholder="t('mcpServiceDialog.serviceUrlPlaceholder')" />
</t-form-item>
<!-- Stdio Config -->
<template v-if="formData.transport_type === 'stdio'">
- <t-form-item label="命令" name="stdio_config.command">
+ <t-form-item :label="t('mcpServiceDialog.command')" name="stdio_config.command">
<t-radio-group v-model="formData.stdio_config.command">
<t-radio value="uvx">uvx</t-radio>
<t-radio value="npx">npx</t-radio>
</t-radio-group>
</t-form-item>
- <t-form-item label="参数" name="stdio_config.args">
+ <t-form-item :label="t('mcpServiceDialog.args')" name="stdio_config.args">
<div class="args-input-container">
<div
v-for="(arg, index) in formData.stdio_config.args"
@@ -60,7 +60,7 @@
>
<t-input
v-model="formData.stdio_config.args[index]"
- :placeholder="`参数 ${index + 1}`"
+ :placeholder="t('mcpServiceDialog.argPlaceholder', { index: index + 1 })"
class="arg-input"
/>
<t-button
@@ -79,12 +79,12 @@
class="add-arg-btn"
>
<template #icon><t-icon name="add" /></template>
- 添加参数
+ {{ t('mcpServiceDialog.addArg') }}
</t-button>
</div>
</t-form-item>
- <t-form-item label="环境变量">
+ <t-form-item :label="t('mcpServiceDialog.envVars')">
<div class="env-vars-container">
<div
v-for="(value, key, index) in formData.env_vars"
@@ -93,13 +93,13 @@
>
<t-input
v-model="envVarKeys[index]"
- placeholder="变量名"
+ :placeholder="t('mcpServiceDialog.envKeyPlaceholder')"
class="env-key-input"
@blur="updateEnvVarKey(index, envVarKeys[index])"
/>
<t-input
v-model="formData.env_vars[key]"
- placeholder="变量值"
+ :placeholder="t('mcpServiceDialog.envValuePlaceholder')"
type="password"
class="env-value-input"
/>
@@ -118,38 +118,38 @@
class="add-env-var-btn"
>
<template #icon><t-icon name="add" /></template>
- 添加环境变量
+ {{ t('mcpServiceDialog.addEnvVar') }}
</t-button>
</div>
</t-form-item>
</template>
- <t-form-item label="启用服务" name="enabled">
+ <t-form-item :label="t('mcpServiceDialog.enableService')" name="enabled">
<t-switch v-model="formData.enabled" />
</t-form-item>
<!-- Authentication Config -->
<t-collapse :default-value="[]">
- <t-collapse-panel header="认证配置" value="auth">
- <t-form-item label="API Key">
+ <t-collapse-panel :header="t('mcpServiceDialog.authConfig')" value="auth">
+ <t-form-item :label="t('mcpServiceDialog.apiKey')">
<t-input
v-model="formData.auth_config.api_key"
type="password"
- placeholder="可选"
+ :placeholder="t('mcpServiceDialog.optional')"
/>
</t-form-item>
- <t-form-item label="Bearer Token">
+ <t-form-item :label="t('mcpServiceDialog.bearerToken')">
<t-input
v-model="formData.auth_config.token"
type="password"
- placeholder="可选"
+ :placeholder="t('mcpServiceDialog.optional')"
/>
</t-form-item>
</t-collapse-panel>
<!-- Advanced Config -->
- <t-collapse-panel header="高级配置" value="advanced">
- <t-form-item label="超时时间(秒)">
+ <t-collapse-panel :header="t('mcpServiceDialog.advancedConfig')" value="advanced">
+ <t-form-item :label="t('mcpServiceDialog.timeoutSec')">
<t-input-number
v-model="formData.advanced_config.timeout"
:min="1"
@@ -157,7 +157,7 @@
placeholder="30"
/>
</t-form-item>
- <t-form-item label="重试次数">
+ <t-form-item :label="t('mcpServiceDialog.retryCount')">
<t-input-number
v-model="formData.advanced_config.retry_count"
:min="0"
@@ -165,7 +165,7 @@
placeholder="3"
/>
</t-form-item>
- <t-form-item label="重试延迟(秒)">
+ <t-form-item :label="t('mcpServiceDialog.retryDelaySec')">
<t-input-number
v-model="formData.advanced_config.retry_delay"
:min="0"
@@ -183,6 +183,7 @@
import { ref, watch, computed } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import type { FormInstanceFunctions, FormRule } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
import {
createMCPService,
updateMCPService,
@@ -205,6 +206,7 @@ const emit = defineEmits<Emits>()
const formRef = ref<FormInstanceFunctions>()
const submitting = ref(false)
+const { t } = useI18n()
const formData = ref({
name: '',
@@ -232,24 +234,24 @@ const formData = ref({
const envVarKeys = ref<string[]>([])
const rules: Record<string, FormRule[]> = {
- name: [{ required: true, message: '请输入服务名称', type: 'error' }],
- transport_type: [{ required: true, message: '请选择传输类型', type: 'error' }],
+ name: [{ required: true, message: t('mcpServiceDialog.rules.nameRequired') as string, type: 'error' }],
+ transport_type: [{ required: true, message: t('mcpServiceDialog.rules.transportRequired') as string, type: 'error' }],
url: [
{
validator: (val: string) => {
if (formData.value.transport_type !== 'stdio') {
if (!val || val.trim() === '') {
- return { result: false, message: '请输入服务 URL', type: 'error' }
+ return { result: false, message: t('mcpServiceDialog.rules.urlRequired') as string, type: 'error' }
}
// Basic URL validation
try {
new URL(val)
- return { result: true }
+ return { result: true, message: '', type: 'success' }
} catch {
- return { result: false, message: '请输入有效的 URL', type: 'error' }
+ return { result: false, message: t('mcpServiceDialog.rules.urlInvalid') as string, type: 'error' }
}
}
- return { result: true }
+ return { result: true, message: '', type: 'success' }
}
}
],
@@ -258,10 +260,10 @@ const rules: Record<string, FormRule[]> = {
validator: (val: string) => {
if (formData.value.transport_type === 'stdio') {
if (!val || (val !== 'uvx' && val !== 'npx')) {
- return { result: false, message: '请选择命令 (uvx 或 npx)', type: 'error' }
+ return { result: false, message: t('mcpServiceDialog.rules.commandRequired') as string, type: 'error' }
}
}
- return { result: true }
+ return { result: true, message: '', type: 'success' }
}
}
],
@@ -270,10 +272,10 @@ const rules: Record<string, FormRule[]> = {
validator: (val: string[]) => {
if (formData.value.transport_type === 'stdio') {
if (!val || val.length === 0 || val.every(arg => !arg || arg.trim() === '')) {
- return { result: false, message: '请至少输入一个参数', type: 'error' }
+ return { result: false, message: t('mcpServiceDialog.rules.argsRequired') as string, type: 'error' }
}
}
- return { result: true }
+ return { result: true, message: '', type: 'success' }
}
}
]
@@ -435,7 +437,7 @@ const handleSubmit = async () => {
const args = formData.value.stdio_config.args.filter(arg => arg && arg.trim() !== '')
data.stdio_config = {
command: formData.value.stdio_config.command,
- args: args.length > 0 ? args : undefined
+ args
}
// Filter out empty env vars
const envVars: Record<string, string> = {}
@@ -451,16 +453,16 @@ const handleSubmit = async () => {
if (props.mode === 'add') {
await createMCPService(data)
- MessagePlugin.success('MCP 服务已创建')
+ MessagePlugin.success(t('mcpServiceDialog.toasts.created'))
} else {
await updateMCPService(props.service!.id, data)
- MessagePlugin.success('MCP 服务已更新')
+ MessagePlugin.success(t('mcpServiceDialog.toasts.updated'))
}
emit('success')
} catch (error) {
MessagePlugin.error(
- props.mode === 'add' ? '创建 MCP 服务失败' : '更新 MCP 服务失败'
+ props.mode === 'add' ? (t('mcpServiceDialog.toasts.createFailed') as string) : (t('mcpServiceDialog.toasts.updateFailed') as string)
)
console.error('Failed to save MCP service:', error)
} finally {
diff --git a/frontend/src/views/settings/components/McpTestResult.vue b/frontend/src/views/settings/components/McpTestResult.vue
index b668eb228..fb37412cc 100644
--- a/frontend/src/views/settings/components/McpTestResult.vue
+++ b/frontend/src/views/settings/components/McpTestResult.vue
@@ -1,7 +1,7 @@
<template>
<t-dialog
v-model:visible="dialogVisible"
- :header="`测试结果: ${serviceName}`"
+ :header="$t('mcp.testResult.title', { name: serviceName })"
width="600px"
:footer="false"
>
@@ -10,11 +10,11 @@
<div class="status-section">
<div v-if="result.success" class="status-success">
<t-icon name="check-circle-filled" size="20px" />
- <span class="status-text">连接成功</span>
+ <span class="status-text">{{ $t('mcp.testResult.connectionSuccess') }}</span>
</div>
<div v-else class="status-error">
<t-icon name="close-circle-filled" size="20px" />
- <span class="status-text">连接失败</span>
+ <span class="status-text">{{ $t('mcp.testResult.connectionFailed') }}</span>
</div>
<p v-if="result.message" class="status-message">{{ result.message }}</p>
</div>
@@ -24,7 +24,7 @@
<!-- Tools List -->
<div v-if="result.tools && result.tools.length > 0" class="section">
<div class="section-header">
- <h3>可用工具</h3>
+ <h3>{{ $t('mcp.testResult.toolsTitle') }}</h3>
<t-tag theme="primary" variant="light" size="small">{{ result.tools.length }}</t-tag>
</div>
<div class="tools-grid">
@@ -51,11 +51,11 @@
</div>
<div v-if="expandedToolIndex === index" class="tool-card-content">
<div v-if="tool.description" class="tool-description">
- <div class="label">描述</div>
+ <div class="label">{{ $t('mcp.testResult.descriptionLabel') }}</div>
<div class="value">{{ tool.description }}</div>
</div>
<div v-if="tool.inputSchema" class="tool-schema">
- <div class="label">参数结构</div>
+ <div class="label">{{ $t('mcp.testResult.schemaLabel') }}</div>
<div class="schema-content">
<pre>{{ formatSchema(tool.inputSchema) }}</pre>
</div>
@@ -68,7 +68,7 @@
<!-- Resources List -->
<div v-if="result.resources && result.resources.length > 0" class="section">
<div class="section-header">
- <h3>可用资源</h3>
+ <h3>{{ $t('mcp.testResult.resourcesTitle') }}</h3>
<t-tag theme="primary" variant="light" size="small">{{ result.resources.length }}</t-tag>
</div>
<div class="resources-grid">
@@ -107,13 +107,13 @@
"
class="empty-state"
>
- <t-empty description="该服务未提供工具或资源" />
+ <t-empty :description="$t('mcp.testResult.emptyDescription')" />
</div>
</div>
</div>
<template #footer>
- <t-button @click="handleClose">关闭</t-button>
+ <t-button @click="handleClose">{{ $t('common.close') }}</t-button>
</template>
</t-dialog>
</template>
@@ -121,6 +121,7 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import type { MCPTestResult } from '@/api/mcp-service'
+import { useI18n } from 'vue-i18n'
interface Props {
visible: boolean
@@ -136,7 +137,7 @@ const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const expandedToolIndex = ref<number | null>(null)
-
+const { t } = useI18n()
const dialogVisible = computed({
get: () => props.visible,
diff --git a/frontend/src/views/tenant/TenantInfo.vue b/frontend/src/views/tenant/TenantInfo.vue
deleted file mode 100644
index f89850d84..000000000
--- a/frontend/src/views/tenant/TenantInfo.vue
+++ /dev/null
@@ -1,465 +0,0 @@
-<template>
- <div class="tenant-info-container">
- <div class="tenant-header">
- <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>
- <div class="card-title">用户信息</div>
- </template>
- <div class="info-content">
- <t-descriptions :column="1" layout="vertical">
- <t-descriptions-item label="用户 ID">
- {{ userInfo?.id }}
- </t-descriptions-item>
- <t-descriptions-item label="用户名">
- {{ userInfo?.username }}
- </t-descriptions-item>
- <t-descriptions-item label="邮箱">
- {{ userInfo?.email }}
- </t-descriptions-item>
- <t-descriptions-item label="创建时间">
- {{ formatDate(userInfo?.created_at) }}
- </t-descriptions-item>
- </t-descriptions>
- </div>
- </t-card>
-
- <!-- 租户信息卡片 -->
- <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="租户 ID">
- {{ tenantInfo?.id }}
- </t-descriptions-item>
- <t-descriptions-item label="租户名称">
- {{ tenantInfo?.name }}
- </t-descriptions-item>
- <t-descriptions-item label="描述">
- {{ tenantInfo?.description || '暂无描述' }}
- </t-descriptions-item>
- <t-descriptions-item label="业务">
- {{ tenantInfo?.business || '暂无' }}
- </t-descriptions-item>
- <t-descriptions-item label="状态">
- <t-tag
- :theme="getStatusTheme(tenantInfo?.status)"
- variant="light"
- >
- {{ getStatusText(tenantInfo?.status) }}
- </t-tag>
- </t-descriptions-item>
- <t-descriptions-item label="创建时间">
- {{ formatDate(tenantInfo?.created_at) }}
- </t-descriptions-item>
- </t-descriptions>
- </div>
- </t-card>
-
- <!-- API Key 卡片 -->
- <t-card class="info-card" :bordered="false">
- <template #header>
- <div class="card-header-with-actions">
- <div class="card-title">API Key</div>
- </div>
- </template>
- <div class="api-key-content">
- <t-input
- v-model="displayApiKey"
- readonly
- class="api-key-input"
- :type="showApiKey ? 'text' : 'password'"
- />
- <t-alert theme="warning" :close="false" class="api-warning">
- <template #icon>
- <t-icon name="error-circle" />
- </template>
- 请妥善保管您的 API Key,不要在公共场所或代码仓库中暴露
- </t-alert>
- </div>
- </t-card>
-
- <!-- 存储信息卡片 -->
- <t-card
- class="info-card"
- :bordered="false"
- v-if="tenantInfo?.storage_quota !== undefined"
- >
- <template #header>
- <div class="card-title">存储信息</div>
- </template>
- <div class="storage-content">
- <t-descriptions :column="1" layout="vertical">
- <t-descriptions-item label="存储配额">
- {{ formatBytes(tenantInfo.storage_quota) }}
- </t-descriptions-item>
- <t-descriptions-item label="已使用">
- {{ formatBytes(tenantInfo.storage_used || 0) }}
- </t-descriptions-item>
- <t-descriptions-item label="使用率">
- <div class="usage-info">
- <span class="usage-text">{{ getUsagePercentage() }}%</span>
- <t-progress
- :percentage="getUsagePercentage()"
- :show-info="false"
- size="medium"
- :theme="getUsagePercentage() > 80 ? 'warning' : 'success'"
- />
- </div>
- </t-descriptions-item>
- </t-descriptions>
- </div>
- </t-card>
- </div>
-
- <!-- 加载状态 -->
- <div v-if="loading" class="loading-container">
- <t-loading size="large" />
- <p class="loading-text">正在加载账户信息...</p>
- </div>
-
- <!-- 错误状态 -->
- <div v-if="error" class="error-container">
- <t-result theme="error" title="加载失败" :description="error">
- <template #extra>
- <t-button theme="primary" @click="loadTenantInfo">重试</t-button>
- </template>
- </t-result>
- </div>
- </div>
-</template>
-
-<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)
-const showApiExample = ref(false)
-
-// API 基础 URL
-const apiBaseUrl = window.location.origin
-
-// 计算属性
-const displayApiKey = computed(() => {
- if (!tenantInfo.value?.api_key) return ''
- return tenantInfo.value.api_key
-})
-
-// API示例代码
-const apiExampleCode = computed(() => {
- return `curl -X GET "${apiBaseUrl}/api/v1/tenants/${tenantInfo.value?.id}" \\
- -H "Content-Type: application/json" \\
- -H "X-API-Key: ${tenantInfo.value?.api_key}"`
-})
-
-// 方法
-const loadTenantInfo = async () => {
- try {
- loading.value = true
- error.value = ''
-
- // 并行获取用户信息和系统信息
- 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 = userResponse.message || '获取用户信息失败'
- }
-
- if (systemResponse.data) {
- systemInfo.value = systemResponse.data
- }
- } catch (err: any) {
- error.value = err.message || '网络错误,请稍后重试'
- } finally {
- loading.value = false
- }
-}
-
-const toggleApiKeyVisibility = () => {
- showApiKey.value = !showApiKey.value
-}
-
-const copyApiKey = async () => {
- if (!tenantInfo.value?.api_key) return
-
- try {
- await navigator.clipboard.writeText(tenantInfo.value.api_key)
- // 使用TDesign的消息组件
- import('tdesign-vue-next').then(({ MessagePlugin }) => {
- MessagePlugin.success('API Key 已复制到剪贴板')
- })
- } catch (err) {
- // 降级到传统方式
- const textArea = document.createElement('textarea')
- textArea.value = tenantInfo.value.api_key
- document.body.appendChild(textArea)
- textArea.select()
- document.execCommand('copy')
- document.body.removeChild(textArea)
- import('tdesign-vue-next').then(({ MessagePlugin }) => {
- MessagePlugin.success('API Key 已复制到剪贴板')
- })
- }
-}
-
-const getStatusText = (status: string | undefined) => {
- switch (status) {
- case 'active':
- return '活跃'
- case 'inactive':
- return '未激活'
- case 'suspended':
- return '已暂停'
- default:
- return '未知'
- }
-}
-
-const getStatusTheme = (status: string | undefined) => {
- switch (status) {
- case 'active':
- return 'success'
- case 'inactive':
- return 'warning'
- case 'suspended':
- return 'danger'
- default:
- return 'default'
- }
-}
-
-const formatDate = (dateStr: string | undefined) => {
- if (!dateStr) return '未知'
-
- try {
- const date = new Date(dateStr)
- return date.toLocaleString('zh-CN', {
- year: 'numeric',
- month: '2-digit',
- day: '2-digit',
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit'
- })
- } catch {
- return '格式错误'
- }
-}
-
-const formatBytes = (bytes: number) => {
- if (bytes === 0) return '0 B'
-
- const k = 1024
- const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
- const i = Math.floor(Math.log(bytes) / Math.log(k))
-
- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
-}
-
-const getUsagePercentage = () => {
- if (!tenantInfo.value?.storage_quota || tenantInfo.value.storage_quota === 0) {
- return 0
- }
-
- const used = tenantInfo.value.storage_used || 0
- const percentage = (used / tenantInfo.value.storage_quota) * 100
- return Math.min(Math.round(percentage * 100) / 100, 100) // 保留两位小数,最大100%
-}
-
-// 生命周期
-onMounted(() => {
- loadTenantInfo()
-})
-</script>
-
-<style lang="less" scoped>
-.tenant-info-container {
- padding: 20px;
- background-color: #fff;
- margin: 0 20px 0 20px;
- height: calc(100vh);
- overflow-y: auto;
- box-sizing: border-box;
- flex: 1;
-}
-
-.tenant-header {
- margin-bottom: 20px;
- border-bottom: 1px solid #f0f0f0;
- padding-bottom: 16px;
-
- h2 {
- font-size: 20px;
- font-weight: 600;
- color: #000000;
- margin: 0 0 8px 0;
- }
-
- .tenant-subtitle {
- font-size: 14px;
- color: #666666;
- margin: 0;
- }
-}
-
-.tenant-content {
- display: grid;
- gap: 20px;
- grid-template-columns: 1fr;
-}
-
-.info-card {
- margin-bottom: 20px;
-
- .card-title {
- font-size: 16px;
- font-weight: 600;
- color: #07C05F;
- }
-
- .card-header-with-actions {
- display: flex;
- justify-content: space-between;
- align-items: center;
- }
-}
-
-.info-content,
-.api-key-content,
-.storage-content,
-.doc-content {
- margin-top: 0;
-}
-
-.api-key-input {
- margin-bottom: 16px;
- font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
-}
-
-.api-warning {
- margin-top: 16px;
-}
-
-.usage-info {
- display: flex;
- flex-direction: column;
- gap: 8px;
-
- .usage-text {
- font-weight: 500;
- color: #000000;
- }
-}
-
-.loading-container {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 60px 24px;
- text-align: center;
-
- .loading-text {
- margin-top: 16px;
- color: #666666;
- font-size: 14px;
- }
-}
-
-.error-container {
- padding: 40px;
- text-align: center;
-}
-
-/* 响应式设计 */
-@media (max-width: 768px) {
- .tenant-info-container {
- padding: 16px;
- margin: 10px;
- height: calc(100vh - 20px);
- }
-
- .tenant-header h2 {
- font-size: 18px;
- }
-
- .card-header-with-actions {
- flex-direction: column;
- align-items: flex-start !important;
- gap: 12px;
- }
-
- .commit-info {
- color: #666;
- font-size: 12px;
- margin-left: 8px;
- }
-}
-
-/* 覆盖TDesign组件样式 */
-:deep(.t-card) {
- border: 1px solid #e5e7eb;
-}
-
-:deep(.t-descriptions-item__label) {
- font-weight: 500;
- color: #374151;
-}
-
-:deep(.t-descriptions-item__content) {
- color: #000000;
-}
-
-:deep(.t-input__inner) {
- font-family: inherit;
-}
-
-:deep(.code-textarea .t-textarea__inner) {
- font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
- font-size: 13px;
- line-height: 1.4;
-}
-</style>
diff --git a/internal/container/container.go b/internal/container/container.go
index ea373bd93..697024dbf 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -124,13 +124,11 @@ func BuildContainer(container *dig.Container) *dig.Container {
// SessionService is created after AgentService and passes itself to AgentService.CreateAgentEngine when needed
must(container.Provide(service.NewSessionService))
- // Chat pipeline components for processing chat requests
- must(container.Provide(chatpipline.NewEventManager))
- // Ensure Async task components are registered before invoking plugins that depend on KnowledgeService
- // KnowledgeService depends on *asynq.Client, and plugins (like PluginSearch) are invoked below.
must(container.Provide(router.NewAsyncqClient))
must(container.Provide(router.NewAsynqServer))
- must(container.Invoke(router.RunAsynqServer))
+
+ // Chat pipeline components for processing chat requests
+ must(container.Provide(chatpipline.NewEventManager))
must(container.Invoke(chatpipline.NewPluginTracing))
must(container.Invoke(chatpipline.NewPluginSearch))
must(container.Invoke(chatpipline.NewPluginRerank))
@@ -162,8 +160,6 @@ func BuildContainer(container *dig.Container) *dig.Container {
// Router configuration
must(container.Provide(router.NewRouter))
- must(container.Provide(router.NewAsyncqClient))
- must(container.Provide(router.NewAsynqServer))
must(container.Invoke(router.RunAsynqServer))
return container