feat: Add web search functionality and enhance agent mode integration

- Introduced web search configuration in config.yaml, allowing multiple providers with specific settings.
- Updated InputField component to manage agent mode and web search toggles, improving user interaction.
- Enhanced chat API to include web search status in requests, enabling dynamic query handling.
- Implemented backend support for web search integration, merging results with knowledge base queries.
- Added tenant-level web search configuration management, allowing customization per tenant.
This commit is contained in:
wizardchen
2025-11-10 03:14:12 +08:00
parent 1313f4dfbb
commit 07a8c1de4c
46 changed files with 2574 additions and 56 deletions
+9 -1
View File
@@ -28,7 +28,7 @@ export function useStream() {
let renderTimer: number | null = null
// 启动流式请求
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; agent_enabled?: boolean; summary_model_id?: string; method: string; url: string }) => {
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; agent_enabled?: boolean; web_search_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; method: string; url: string }) => {
// 重置状态
output.value = '';
error.value = null;
@@ -69,10 +69,18 @@ export function useStream() {
if (params.knowledge_base_ids !== undefined && params.knowledge_base_ids.length > 0) {
postBody.knowledge_base_ids = params.knowledge_base_ids;
}
// Include web_search_enabled if provided
if (params.web_search_enabled !== undefined) {
postBody.web_search_enabled = params.web_search_enabled;
}
// Include summary_model_id if provided (for non-Agent mode)
if (params.summary_model_id) {
postBody.summary_model_id = params.summary_model_id;
}
// Include mcp_service_ids if provided (for Agent mode)
if (params.mcp_service_ids !== undefined && params.mcp_service_ids.length > 0) {
postBody.mcp_service_ids = params.mcp_service_ids;
}
await fetchEventSource(url, {
method: params.method,
+41
View File
@@ -0,0 +1,41 @@
import { get, put } from '@/utils/request'
// WebSearchProviderConfig represents information about a web search provider
export interface WebSearchProviderConfig {
id: string
name: string
free: boolean
requires_api_key: boolean
description?: string
api_url?: string
}
// WebSearchConfig represents the web search configuration for a tenant
export interface WebSearchConfig {
provider: string
api_key?: string
max_results: number
include_date: boolean
compression_method: string
blacklist: string[]
embedding_model_id?: string
embedding_dimension?: number
rerank_model_id?: string
document_fragments?: number
}
// Get web search providers
export function getWebSearchProviders() {
return get('/api/v1/web-search/providers')
}
// Get tenant web search config
export function getTenantWebSearchConfig() {
return get('/api/v1/tenants/web-search-config')
}
// Update tenant web search config
export function updateTenantWebSearchConfig(config: WebSearchConfig) {
return put('/api/v1/tenants/web-search-config', config)
}
+458 -46
View File
@@ -17,6 +17,9 @@ const uiStore = useUIStore();
let query = ref("");
const showKbSelector = ref(false);
const atButtonRef = ref<HTMLElement>();
const showAgentModeSelector = ref(false);
const agentModeButtonRef = ref<HTMLElement>();
const agentModeDropdownStyle = ref<Record<string, string>>({});
const props = defineProps({
isReplying: {
@@ -34,6 +37,7 @@ const props = defineProps({
});
const isAgentEnabled = computed(() => settingsStore.isAgentEnabled);
const isWebSearchEnabled = computed(() => settingsStore.isWebSearchEnabled);
const selectedKbIds = computed(() => settingsStore.settings.selectedKnowledgeBases || []);
// 获取已选择的知识库信息
@@ -193,6 +197,11 @@ const closeModelSelector = () => {
showModelSelector.value = false;
};
// 关闭 Agent 模式选择器(点击外部)
const closeAgentModeSelector = () => {
showAgentModeSelector.value = false;
};
onMounted(() => {
loadKnowledgeBases();
@@ -211,16 +220,21 @@ onMounted(() => {
// 监听点击外部关闭下拉菜单
document.addEventListener('click', closeModelSelector);
document.addEventListener('click', closeAgentModeSelector);
// 监听窗口大小变化,重新计算位置
window.addEventListener('resize', () => {
if (showModelSelector.value) {
updateModelDropdownPosition();
}
if (showAgentModeSelector.value) {
updateAgentModeDropdownPosition();
}
});
});
onUnmounted(() => {
document.removeEventListener('click', closeModelSelector);
document.removeEventListener('click', closeAgentModeSelector);
});
// 监听路由变化
@@ -317,6 +331,51 @@ const updateModelDropdownPosition = () => {
};
};
// 计算 Agent 模式下拉菜单位置
const updateAgentModeDropdownPosition = () => {
const anchor = agentModeButtonRef.value;
if (!anchor) {
agentModeDropdownStyle.value = {
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)'
};
return;
}
const rect = anchor.getBoundingClientRect();
const dropdownWidth = 200;
const offsetY = 8;
// 计算位置:默认在按钮下方
let top = rect.bottom + offsetY;
let left = rect.left;
// 检查右侧边界
if (left + dropdownWidth > window.innerWidth) {
left = window.innerWidth - dropdownWidth - 10;
}
// 检查下方空间
const dropdownMaxHeight = 150;
if (top + dropdownMaxHeight > window.innerHeight) {
// 如果下方空间不足,显示在按钮上方
top = rect.top - dropdownMaxHeight - offsetY;
if (top < 10) {
top = 10;
}
}
agentModeDropdownStyle.value = {
position: 'fixed',
top: `${Math.round(top)}px`,
left: `${Math.round(left)}px`,
width: `${dropdownWidth}px`
};
};
const toggleModelSelector = () => {
showModelSelector.value = !showModelSelector.value;
if (showModelSelector.value) {
@@ -326,6 +385,36 @@ const toggleModelSelector = () => {
}
}
const toggleAgentModeSelector = () => {
// 如果 Agent 未就绪,显示提示
if (!settingsStore.isAgentReady && !isAgentEnabled.value) {
toggleAgentMode();
return;
}
showAgentModeSelector.value = !showAgentModeSelector.value;
if (showAgentModeSelector.value) {
nextTick(() => {
updateAgentModeDropdownPosition();
});
}
}
const selectAgentMode = (mode: 'normal' | 'agent') => {
if (mode === 'agent' && !settingsStore.isAgentReady) {
toggleAgentMode();
showAgentModeSelector.value = false;
return;
}
const shouldEnableAgent = mode === 'agent';
if (shouldEnableAgent !== isAgentEnabled.value) {
settingsStore.toggleAgent(shouldEnableAgent);
MessagePlugin.success(shouldEnableAgent ? '已切换到 Agent 模式' : '已切换到普通模式');
}
showAgentModeSelector.value = false;
}
const clearvalue = () => {
query.value = "";
}
@@ -389,6 +478,13 @@ const toggleAgentMode = () => {
MessagePlugin.success(message);
}
const toggleWebSearch = () => {
const currentValue = settingsStore.isWebSearchEnabled;
const newValue = !currentValue;
settingsStore.toggleWebSearch(newValue);
MessagePlugin.success(newValue ? '网络搜索已开启' : '网络搜索已关闭');
}
const toggleKbSelector = () => {
showKbSelector.value = !showKbSelector.value;
}
@@ -437,41 +533,142 @@ onBeforeRouteUpdate((to, from, next) => {
<div class="control-bar">
<!-- 左侧控制按钮 -->
<div class="control-left">
<!-- Agent 模式按钮 -->
<t-tooltip
placement="top"
:show-arrow="true"
:duration="0"
<!-- Agent 模式切换按钮 -->
<div
ref="agentModeButtonRef"
class="control-btn agent-mode-btn"
:class="{
'active': isAgentEnabled,
'agent-active': isAgentEnabled
}"
@click.stop="toggleAgentModeSelector"
>
<template #content>
<div style="display: flex; flex-direction: column; gap: 4px; align-items: flex-start;">
<span>
{{ isAgentEnabled ? 'Agent 模式(已启用)' : (settingsStore.isAgentReady ? 'Agent 模式(已禁用,点击启用)' : 'Agent 未就绪,请先完成配置') }}
</span>
<a
href="#"
@click.prevent="handleGoToAgentSettings"
style="color: #07C05F; text-decoration: none; font-size: 12px; cursor: pointer;"
@mouseenter="(e) => e.target.style.textDecoration = 'underline'"
@mouseleave="(e) => e.target.style.textDecoration = 'none'"
>
去设置 Agent →
</a>
</div>
</template>
<div
class="control-btn agent-btn"
:class="{
'active': isAgentEnabled,
'disabled': !isAgentEnabled && !settingsStore.isAgentReady
}"
@click="toggleAgentMode"
<img
v-if="isAgentEnabled"
:src="getImgSrc('agent-active.svg')"
alt="Agent模式"
class="control-icon agent-icon"
/>
<svg
v-else
width="18"
height="18"
viewBox="0 0 16 16"
fill="currentColor"
class="control-icon normal-mode-icon"
>
<img
:src="isAgentEnabled ? getImgSrc('agent-active.svg') : getImgSrc('agent.svg')"
alt="Agent"
class="control-icon"
/>
<path d="M8 0a8 8 0 1 0 0 16A8 8 0 0 0 8 0zM1.5 8a6.5 6.5 0 1 1 13 0 6.5 6.5 0 0 1-13 0z"/>
<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 模式' : '普通模式' }}
</span>
<svg
width="12"
height="12"
viewBox="0 0 12 12"
fill="currentColor"
class="dropdown-arrow"
:class="{ 'rotate': showAgentModeSelector }"
>
<path d="M2.5 4.5L6 8L9.5 4.5H2.5Z"/>
</svg>
</div>
<!-- Agent 模式选择下拉菜单 -->
<Teleport to="body">
<div v-if="showAgentModeSelector" class="agent-mode-selector-overlay" @click="closeAgentModeSelector">
<div
class="agent-mode-selector-dropdown"
:style="agentModeDropdownStyle"
@click.stop
>
<div
class="agent-mode-option"
:class="{ 'selected': !isAgentEnabled }"
@click="selectAgentMode('normal')"
>
<div class="agent-mode-option-main">
<span class="agent-mode-option-name">普通模式</span>
<span class="agent-mode-option-desc">基于知识库的 RAG 问答</span>
</div>
<svg
v-if="!isAgentEnabled"
width="16"
height="16"
viewBox="0 0 16 16"
fill="currentColor"
class="check-icon"
>
<path d="M13.5 4.5L6 12L2.5 8.5L3.5 7.5L6 10L12.5 3.5L13.5 4.5Z"/>
</svg>
</div>
<div
class="agent-mode-option"
:class="{
'selected': isAgentEnabled,
'disabled': !settingsStore.isAgentReady && !isAgentEnabled
}"
@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>
</div>
<svg
v-if="isAgentEnabled"
width="16"
height="16"
viewBox="0 0 16 16"
fill="currentColor"
class="check-icon"
>
<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-icon name="error-circle" class="warning-icon" />
</t-tooltip>
</div>
</div>
<div v-if="!settingsStore.isAgentReady && !isAgentEnabled" class="agent-mode-footer">
<a
href="#"
@click.prevent="handleGoToAgentSettings"
class="agent-mode-link"
>
前往设置 →
</a>
</div>
</div>
</div>
</Teleport>
<!-- WebSearch 开关按钮 -->
<t-tooltip
:content="isWebSearchEnabled ? '关闭网络搜索' : '开启网络搜索'"
placement="top"
>
<div
class="control-btn websearch-btn"
:class="{ 'active': isWebSearchEnabled }"
@click.stop="toggleWebSearch"
>
<svg
width="18"
height="18"
viewBox="0 0 18 18"
fill="none"
xmlns="http://www.w3.org/2000/svg"
class="control-icon websearch-icon"
:class="{ 'active': isWebSearchEnabled }"
>
<circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.2" fill="none"/>
<path d="M 9 2 A 3.5 7 0 0 0 9 16" stroke="currentColor" stroke-width="1.2" fill="none"/>
<path d="M 9 2 A 3.5 7 0 0 1 9 16" stroke="currentColor" stroke-width="1.2" fill="none"/>
<line x1="2.94" y1="5.5" x2="15.06" y2="5.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/>
<line x1="2.94" y1="12.5" x2="15.06" y2="12.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/>
</svg>
</div>
</t-tooltip>
@@ -719,30 +916,76 @@ const getImgSrc = (url: string) => {
}
}
.agent-btn {
width: 28px;
.agent-mode-btn {
height: 28px;
padding: 0;
&.active {
background: rgba(7, 192, 95, 0.1);
padding: 0 10px;
min-width: auto;
font-weight: 500;
border: 1.5px solid transparent;
transition: all 0.2s ease;
position: relative;
&.active,
&.agent-active {
background: linear-gradient(135deg, rgba(7, 192, 95, 0.15) 0%, rgba(7, 192, 95, 0.1) 100%);
border-color: rgba(7, 192, 95, 0.4);
box-shadow: 0 2px 6px rgba(7, 192, 95, 0.12);
.agent-mode-text {
color: #07C05F;
font-weight: 600;
}
.agent-icon {
filter: brightness(0) saturate(100%) invert(58%) sepia(87%) saturate(1234%) hue-rotate(95deg) brightness(98%) contrast(89%);
}
.dropdown-arrow {
color: #07C05F;
}
&:hover {
background: rgba(7, 192, 95, 0.15);
background: linear-gradient(135deg, rgba(7, 192, 95, 0.2) 0%, rgba(7, 192, 95, 0.15) 100%);
border-color: rgba(7, 192, 95, 0.6);
box-shadow: 0 3px 10px rgba(7, 192, 95, 0.2);
transform: translateY(-1px);
}
}
&.disabled {
opacity: 0.5;
cursor: not-allowed;
&:not(.agent-active) {
background: rgba(255, 255, 255, 0.8);
border-color: #e0e0e0;
.agent-mode-text {
color: #666;
}
.normal-mode-icon {
color: #666;
}
&:hover {
background: #f5f5f5;
transform: none;
background: rgba(255, 255, 255, 1);
border-color: #b0b0b0;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}
}
}
.agent-icon {
width: 18px;
height: 18px;
flex-shrink: 0;
}
.agent-mode-text {
font-size: 13px;
color: #666;
font-weight: 500;
white-space: nowrap;
margin: 0 4px;
}
.control-icon {
width: 18px;
height: 18px;
@@ -775,6 +1018,48 @@ const getImgSrc = (url: string) => {
color: #07C05F;
}
.websearch-btn {
width: 28px;
height: 28px;
padding: 0;
min-width: auto;
display: flex;
align-items: center;
justify-content: center;
&.active {
background: rgba(7, 192, 95, 0.1);
.websearch-icon {
color: #07C05F;
}
&:hover {
background: rgba(7, 192, 95, 0.15);
}
}
&:not(.active) {
.websearch-icon {
color: #666;
}
&:hover {
background: #f0f0f0;
.websearch-icon {
color: #333;
}
}
}
}
.websearch-icon {
width: 18px;
height: 18px;
transition: all 0.2s ease;
}
.dropdown-arrow {
transition: transform 0.2s ease;
width: 10px;
@@ -1124,4 +1409,131 @@ const getImgSrc = (url: string) => {
background: rgba(82, 196, 26, 0.1);
color: #52c41a;
}
/* Agent 模式选择下拉菜单 */
.agent-mode-selector-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 9998;
}
.agent-mode-selector-dropdown {
z-index: 9999;
background: white;
border-radius: 8px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(7, 192, 95, 0.08);
border: 1px solid #e5e7eb;
overflow: hidden;
padding: 4px;
min-width: 200px;
}
.agent-mode-option {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 14px;
cursor: pointer;
transition: all 0.2s ease;
border-radius: 6px;
position: relative;
margin: 2px 0;
&:hover:not(.disabled) {
background: rgba(7, 192, 95, 0.1);
transform: translateX(2px);
}
&:active:not(.disabled) {
transform: translateX(1px);
}
&.disabled {
opacity: 0.6;
cursor: not-allowed;
&:hover {
background: transparent;
transform: none;
}
}
// 选中状态的选项有更明显的背景
&.selected {
background: rgba(7, 192, 95, 0.06);
.agent-mode-option-name {
color: #07C05F;
font-weight: 700;
}
}
}
.agent-mode-option-main {
display: flex;
flex-direction: column;
gap: 2px;
flex: 1;
min-width: 0;
}
.agent-mode-option-name {
font-size: 14px;
font-weight: 600;
color: #333;
line-height: 1.4;
transition: color 0.2s ease;
}
.agent-mode-option-desc {
font-size: 12px;
color: #999;
line-height: 1.3;
}
.check-icon {
width: 16px;
height: 16px;
color: #07C05F;
flex-shrink: 0;
margin-left: 8px;
}
.agent-mode-warning {
display: flex;
align-items: center;
margin-left: 8px;
.warning-icon {
color: #ff9800;
font-size: 16px;
}
}
.agent-mode-footer {
padding: 8px 12px;
border-top: 1px solid #f0f0f0;
margin-top: 4px;
}
.agent-mode-link {
color: #07C05F;
text-decoration: none;
font-size: 12px;
font-weight: 500;
display: inline-flex;
align-items: center;
gap: 4px;
transition: all 0.2s ease;
&:hover {
color: #00a651;
text-decoration: underline;
}
}
</style>
+13 -2
View File
@@ -10,6 +10,7 @@ interface Settings {
selectedKnowledgeBases: string[]; // 当前选中的知识库ID列表
modelConfig: ModelConfig; // 模型配置
ollamaConfig: OllamaConfig; // Ollama配置
webSearchEnabled: boolean; // 网络搜索是否启用
}
// Agent 配置接口
@@ -71,7 +72,8 @@ const defaultSettings: Settings = {
ollamaConfig: {
baseUrl: "http://localhost:11434",
enabled: true
}
},
webSearchEnabled: false // 默认关闭网络搜索
};
export const useSettingsStore = defineStore("settings", {
@@ -97,6 +99,9 @@ export const useSettingsStore = defineStore("settings", {
// 获取模型配置
modelConfig: (state) => state.settings.modelConfig || defaultSettings.modelConfig,
// 网络搜索是否启用
isWebSearchEnabled: (state) => state.settings.webSearchEnabled || false,
},
actions: {
@@ -224,7 +229,7 @@ export const useSettingsStore = defineStore("settings", {
// 移除单个知识库
removeKnowledgeBase(kbId: string) {
this.settings.selectedKnowledgeBases =
this.settings.selectedKnowledgeBases.filter(id => id !== kbId);
this.settings.selectedKnowledgeBases.filter((id: string) => id !== kbId);
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
},
@@ -238,5 +243,11 @@ export const useSettingsStore = defineStore("settings", {
getSelectedKnowledgeBases(): string[] {
return this.settings.selectedKnowledgeBases || [];
},
// 启用/禁用网络搜索
toggleWebSearch(enabled: boolean) {
this.settings.webSearchEnabled = enabled;
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
},
},
});
+4
View File
@@ -269,6 +269,9 @@ const sendMsg = async (value, modelId = '') => {
// Get agent mode status from settings store
const agentEnabled = useSettingsStoreInstance.isAgentEnabled;
// Get web search status from settings store
const webSearchEnabled = useSettingsStoreInstance.isWebSearchEnabled;
// Get knowledge_base_ids from settings store (selected by user via KnowledgeBaseSelector)
const kbIds = useSettingsStoreInstance.settings.selectedKnowledgeBases || [];
@@ -294,6 +297,7 @@ const sendMsg = async (value, modelId = '') => {
session_id: session_id.value,
knowledge_base_ids: kbIds,
agent_enabled: agentEnabled,
web_search_enabled: webSearchEnabled,
summary_model_id: modelId,
mcp_service_ids: mcpServiceIds,
query: value,
+24 -1
View File
@@ -26,7 +26,23 @@
}]"
@click="handleNavClick(item)"
>
<t-icon :name="item.icon" class="nav-icon" />
<!-- 网络搜索使用自定义 SVG 图标 -->
<svg
v-if="item.key === 'websearch'"
width="18"
height="18"
viewBox="0 0 18 18"
fill="none"
xmlns="http://www.w3.org/2000/svg"
class="nav-icon"
>
<circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.2" fill="none"/>
<path d="M 9 2 A 3.5 7 0 0 0 9 16" stroke="currentColor" stroke-width="1.2" fill="none"/>
<path d="M 9 2 A 3.5 7 0 0 1 9 16" stroke="currentColor" stroke-width="1.2" fill="none"/>
<line x1="2.94" y1="5.5" x2="15.06" y2="5.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/>
<line x1="2.94" y1="12.5" x2="15.06" y2="12.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/>
</svg>
<t-icon v-else :name="item.icon" class="nav-icon" />
<span class="nav-label">{{ item.label }}</span>
<t-icon
v-if="item.children && item.children.length > 0"
@@ -78,6 +94,11 @@
<AgentSettings />
</div>
<!-- 网络搜索配置 -->
<div v-if="currentSection === 'websearch'" class="section">
<WebSearchSettings />
</div>
<!-- 系统信息 -->
<div v-if="currentSection === 'system'" class="section">
<SystemInfo />
@@ -118,6 +139,7 @@ import GeneralSettings from './GeneralSettings.vue'
import ModelSettings from './ModelSettings.vue'
import OllamaSettings from './OllamaSettings.vue'
import McpSettings from './McpSettings.vue'
import WebSearchSettings from './WebSearchSettings.vue'
const route = useRoute()
const router = useRouter()
@@ -142,6 +164,7 @@ const navItems = [
},
{ 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: '租户信息' },
@@ -0,0 +1,405 @@
<template>
<div class="websearch-settings">
<div class="section-header">
<h2>网络搜索配置</h2>
<p class="section-description">配置网络搜索功能,在回答问题时可以从互联网获取实时信息补充知识库内容</p>
</div>
<div class="settings-group">
<!-- 搜索引擎提供商 -->
<div class="setting-row">
<div class="setting-info">
<label>搜索引擎提供商</label>
<p class="desc">选择用于网络搜索的搜索引擎服务</p>
</div>
<div class="setting-control">
<t-select
v-model="localProvider"
:loading="loadingProviders"
filterable
placeholder="选择搜索引擎..."
@change="handleProviderChange"
@focus="loadProviders"
style="width: 280px;"
>
<t-option
v-for="provider in providers"
:key="provider.id"
:value="provider.id"
:label="provider.name"
>
<div class="provider-option-wrapper">
<div class="provider-option">
<span class="provider-name">{{ provider.name }}</span>
<div class="provider-tags">
<t-tag v-if="provider.free" size="small" theme="success">免费</t-tag>
<t-tag v-else size="small" theme="warning">付费</t-tag>
<t-tag v-if="provider.requires_api_key" size="small" theme="default">需API密钥</t-tag>
</div>
</div>
<div v-if="provider.description" class="provider-desc">
{{ provider.description }}
</div>
</div>
</t-option>
</t-select>
</div>
</div>
<!-- API 密钥 -->
<div v-if="selectedProvider && selectedProvider.requires_api_key" class="setting-row">
<div class="setting-info">
<label>API 密钥</label>
<p class="desc">输入所选搜索引擎的 API 密钥</p>
</div>
<div class="setting-control">
<t-input
v-model="localAPIKey"
type="password"
placeholder="请输入 API 密钥"
@change="handleAPIKeyChange"
style="width: 400px;"
:show-password="true"
/>
</div>
</div>
<!-- 最大结果数 -->
<div class="setting-row">
<div class="setting-info">
<label>最大结果数</label>
<p class="desc">每次搜索返回的最大结果数量(1-50)</p>
</div>
<div class="setting-control">
<div class="slider-with-value">
<t-slider
v-model="localMaxResults"
:min="1"
:max="50"
:step="1"
:marks="{ 1: '1', 10: '10', 20: '20', 30: '30', 40: '40', 50: '50' }"
@change="handleMaxResultsChange"
style="width: 200px;"
/>
<span class="value-display">{{ localMaxResults }}</span>
</div>
</div>
</div>
<!-- 包含日期 -->
<div class="setting-row">
<div class="setting-info">
<label>包含发布日期</label>
<p class="desc">在搜索结果中包含内容的发布日期信息</p>
</div>
<div class="setting-control">
<t-switch
v-model="localIncludeDate"
@change="handleIncludeDateChange"
/>
</div>
</div>
<!-- 压缩方法 -->
<div class="setting-row">
<div class="setting-info">
<label>压缩方法</label>
<p class="desc">对搜索结果内容的压缩处理方法</p>
</div>
<div class="setting-control">
<t-select
v-model="localCompressionMethod"
@change="handleCompressionMethodChange"
style="width: 280px;"
>
<t-option value="none" label="无压缩">无压缩</t-option>
<t-option value="llm_summary" label="LLM 摘要">LLM 摘要</t-option>
</t-select>
</div>
</div>
<!-- 黑名单 -->
<div class="setting-row vertical">
<div class="setting-info">
<label>URL 黑名单</label>
<p class="desc">排除特定域名或 URL 的搜索结果,每行一个。支持通配符(*)和正则表达式(以/开头和结尾)</p>
</div>
<div class="setting-control">
<t-textarea
v-model="localBlacklistText"
placeholder="例如:&#10;*://*.example.com/*&#10;/example\.(net|org)/"
:autosize="{ minRows: 4, maxRows: 8 }"
@change="handleBlacklistChange"
style="width: 500px;"
/>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { getWebSearchProviders, getTenantWebSearchConfig, updateTenantWebSearchConfig, type WebSearchProviderConfig, type WebSearchConfig } from '@/api/web-search'
// 本地状态
const loadingProviders = ref(false)
const providers = ref<WebSearchProviderConfig[]>([])
const localProvider = ref<string>('')
const localAPIKey = ref<string>('')
const localMaxResults = ref<number>(5)
const localIncludeDate = ref<boolean>(true)
const localCompressionMethod = ref<string>('none')
const localBlacklistText = ref<string>('')
// 计算属性:当前选中的提供商
const selectedProvider = computed(() => {
return providers.value.find(p => p.id === localProvider.value)
})
// 加载提供商列表
const loadProviders = async () => {
if (providers.value.length > 0) {
return // 已加载过
}
loadingProviders.value = true
try {
const response = await getWebSearchProviders()
// request拦截器已经处理了响应,直接使用data字段
if (response.data && Array.isArray(response.data)) {
providers.value = response.data
}
} catch (error: any) {
console.error('Failed to load web search providers:', error)
MessagePlugin.error('加载搜索引擎列表失败: ' + (error.message || '未知错误'))
} finally {
loadingProviders.value = false
}
}
// 加载租户配置
const loadTenantConfig = async () => {
try {
const response = await getTenantWebSearchConfig()
// request拦截器已经处理了响应,直接使用data字段
if (response.data) {
const config = response.data
localProvider.value = config.provider || ''
// API key 在响应中被隐藏,如果是 "***",说明已配置但未返回实际值
localAPIKey.value = config.api_key === '***' ? '***' : config.api_key || ''
localMaxResults.value = config.max_results || 5
localIncludeDate.value = config.include_date !== undefined ? config.include_date : true
localCompressionMethod.value = config.compression_method || 'none'
localBlacklistText.value = (config.blacklist || []).join('\n')
}
} catch (error: any) {
console.error('Failed to load tenant web search config:', error)
// 如果配置不存在,使用默认值(不显示错误)
}
}
// 保存配置
const saveConfig = async () => {
try {
const blacklist = localBlacklistText.value
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0)
const config: WebSearchConfig = {
provider: localProvider.value,
api_key: localAPIKey.value,
max_results: localMaxResults.value,
include_date: localIncludeDate.value,
compression_method: localCompressionMethod.value,
blacklist: blacklist
}
await updateTenantWebSearchConfig(config)
MessagePlugin.success('网络搜索配置已保存')
} catch (error: any) {
console.error('Failed to save web search config:', error)
MessagePlugin.error('保存配置失败: ' + (error.message || '未知错误'))
throw error
}
}
// 防抖保存
let saveTimer: number | null = null
const debouncedSave = () => {
if (saveTimer) {
clearTimeout(saveTimer)
}
saveTimer = window.setTimeout(() => {
saveConfig().catch(() => {
// 错误已在 saveConfig 中处理
})
}, 500)
}
// 处理变化
const handleProviderChange = () => {
debouncedSave()
}
const handleAPIKeyChange = () => {
debouncedSave()
}
const handleMaxResultsChange = () => {
debouncedSave()
}
const handleIncludeDateChange = () => {
debouncedSave()
}
const handleCompressionMethodChange = () => {
debouncedSave()
}
const handleBlacklistChange = () => {
debouncedSave()
}
// 初始化
onMounted(async () => {
await loadProviders()
await loadTenantConfig()
})
</script>
<style lang="less" scoped>
.websearch-settings {
width: 100%;
}
.section-header {
margin-bottom: 32px;
h2 {
font-size: 20px;
font-weight: 600;
color: #333333;
margin: 0 0 8px 0;
}
.section-description {
font-size: 14px;
color: #666666;
margin: 0;
line-height: 1.5;
}
}
.settings-group {
display: flex;
flex-direction: column;
gap: 0;
}
.setting-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
padding: 20px 0;
border-bottom: 1px solid #e5e7eb;
&:last-child {
border-bottom: none;
}
&.vertical {
flex-direction: column;
gap: 12px;
.setting-control {
width: 100%;
max-width: 100%;
}
}
}
.setting-info {
flex: 1;
max-width: 65%;
padding-right: 24px;
label {
font-size: 15px;
font-weight: 500;
color: #333333;
display: block;
margin-bottom: 4px;
}
.desc {
font-size: 13px;
color: #666666;
margin: 0;
line-height: 1.5;
}
}
.setting-control {
flex-shrink: 0;
min-width: 280px;
display: flex;
justify-content: flex-end;
align-items: center;
}
.slider-with-value {
display: flex;
align-items: center;
gap: 12px;
}
.value-display {
min-width: 40px;
text-align: right;
font-size: 14px;
font-weight: 500;
color: #333333;
}
.provider-option-wrapper {
display: flex;
flex-direction: column;
gap: 4px;
padding: 2px 0;
}
.provider-option {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
flex-wrap: wrap;
}
.provider-name {
font-weight: 500;
font-size: 14px;
color: #333;
flex-shrink: 0;
}
.provider-tags {
display: flex;
align-items: center;
gap: 4px;
flex-wrap: wrap;
flex-shrink: 0;
}
.provider-desc {
font-size: 12px;
color: #999;
line-height: 1.4;
margin-top: 2px;
}
</style>