From a28c0f8b01d1962677462ca721f7c103bec0b2c9 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Wed, 12 Nov 2025 01:18:12 +0800 Subject: [PATCH] feat: Integrate web search configuration and enhance input field functionality - Added logic to load and manage web search configuration in the InputField component, ensuring proper handling of web search states. - Implemented user notifications for unconfigured web search settings, guiding users to the appropriate settings page. - Enhanced the AgentStreamDisplay component to improve tooltip content rendering for knowledge base citations. - Updated event data structures to include total duration in milliseconds for better precision in agent completion events. - Refactored citation handling to ensure inline citations are displayed correctly, improving user experience in content rendering. --- frontend/src/components/Input-field.vue | 99 +++++- .../chat/components/AgentStreamDisplay.vue | 324 +++++++++--------- internal/agent/engine.go | 12 +- internal/agent/prompts.go | 14 +- internal/event/event_data.go | 18 +- .../handler/session/agent_stream_handler.go | 4 +- 6 files changed, 288 insertions(+), 183 deletions(-) diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index b35afbea..77246897 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -9,6 +9,7 @@ import { listKnowledgeBases, getKnowledgeBaseById } from '@/api/knowledge-base'; import { stopSession } from '@/api/chat'; import KnowledgeBaseSelector from './KnowledgeBaseSelector.vue'; import { getModel, type ModelConfig } from '@/api/model'; +import { getTenantWebSearchConfig } from '@/api/web-search'; const route = useRoute(); const router = useRouter(); @@ -39,6 +40,7 @@ const props = defineProps({ const isAgentEnabled = computed(() => settingsStore.isAgentEnabled); const isWebSearchEnabled = computed(() => settingsStore.isWebSearchEnabled); const selectedKbIds = computed(() => settingsStore.settings.selectedKnowledgeBases || []); +const isWebSearchConfigured = ref(false); // 获取已选择的知识库信息 const knowledgeBases = ref>([]); @@ -84,6 +86,25 @@ const loadKnowledgeBases = async () => { } }; +const loadWebSearchConfig = async () => { + try { + const response: any = await getTenantWebSearchConfig(); + const config = response?.data; + const configured = !!(config && config.provider); + isWebSearchConfigured.value = configured; + + if (!configured && settingsStore.isWebSearchEnabled) { + settingsStore.toggleWebSearch(false); + } + } catch (error) { + console.error('Failed to load web search config:', error); + isWebSearchConfigured.value = false; + if (settingsStore.isWebSearchEnabled) { + settingsStore.toggleWebSearch(false); + } + } +}; + // 解析模型参数大小 (e.g., "7B", "13B", "70B" -> 7, 13, 70) const parseParameterSize = (paramSize: string | undefined): number => { if (!paramSize) return 0; @@ -204,6 +225,7 @@ const closeAgentModeSelector = () => { onMounted(() => { loadKnowledgeBases(); + loadWebSearchConfig(); // 如果从知识库内部进入,自动选中该知识库 const kbId = (route.params as any)?.kbId as string; @@ -244,6 +266,12 @@ watch(() => route.params.kbId, (newKbId) => { } }); +watch(() => uiStore.showSettingsModal, (visible, prevVisible) => { + if (prevVisible && !visible) { + loadWebSearchConfig(); + } +}); + // 监听知识库选择变化,重新加载模型 watch(selectedKbIds, () => { if (!isAgentEnabled.value) { @@ -429,6 +457,13 @@ const onKeydown = (val: string, event: { e: { preventDefault(): unknown; keyCode } } +const handleGoToWebSearchSettings = () => { + uiStore.openSettings('websearch'); + if (route.path !== '/platform/settings') { + router.push('/platform/settings'); + } +}; + const handleGoToAgentSettings = () => { // 使用 uiStore 打开设置并跳转到 agent 部分 uiStore.openSettings('agent'); @@ -465,7 +500,7 @@ const toggleAgentMode = () => { ]); MessagePlugin.warning({ - content: messageContent, + content: () => messageContent, duration: 5000 }); return @@ -479,11 +514,36 @@ const toggleAgentMode = () => { } 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('a', { + href: '#', + onClick: (e: Event) => { + e.preventDefault(); + handleGoToWebSearchSettings(); + }, + style: 'color: #07C05F; text-decoration: none; font-weight: 500; cursor: pointer; align-self: flex-start;', + onMouseenter: (e: Event) => { + (e.target as HTMLElement).style.textDecoration = 'underline'; + }, + onMouseleave: (e: Event) => { + (e.target as HTMLElement).style.textDecoration = 'none'; + } + }, '去设置 →') + ]); + MessagePlugin.warning({ + content: () => messageContent, + duration: 5000 + }); + return; + } + const currentValue = settingsStore.isWebSearchEnabled; const newValue = !currentValue; settingsStore.toggleWebSearch(newValue); MessagePlugin.success(newValue ? '网络搜索已开启' : '网络搜索已关闭'); -} +}; const toggleKbSelector = () => { showKbSelector.value = !showKbSelector.value; @@ -645,13 +705,17 @@ onBeforeRouteUpdate((to, from, next) => { - + +
{ fill="none" xmlns="http://www.w3.org/2000/svg" class="control-icon websearch-icon" - :class="{ 'active': isWebSearchEnabled }" + :class="{ 'active': isWebSearchEnabled && isWebSearchConfigured }" > @@ -1054,6 +1118,25 @@ const getImgSrc = (url: string) => { } } +:global(.websearch-tooltip-disabled) { + display: flex; + flex-direction: column; + gap: 4px; + max-width: 220px; + font-size: 12px; + color: #666; +} + +:global(.websearch-tooltip-disabled a) { + color: #07C05F; + font-weight: 500; + text-decoration: none; +} + +:global(.websearch-tooltip-disabled a:hover) { + text-decoration: underline; +} + .websearch-icon { width: 18px; height: 18px; diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index 4e886f19..42ff05df 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -171,7 +171,7 @@
加载中...
{{ floatPopup.error }}
-
片段ID: {{ floatPopup.chunkId.slice(0, 25) + '...' }}
+
片段ID: {{ floatPopup.chunkId }}
@@ -189,6 +189,8 @@ import { getChunkByIdOnly } from '@/api/knowledge-base'; const router = useRouter(); // 浮层状态(Web/KB 共用) +const KB_SNIPPET_LIMIT = 600; + const floatPopup = ref<{ visible: boolean; top: number; @@ -222,7 +224,7 @@ const scheduleFloatClose = () => { if (floatCloseTimer) window.clearTimeout(floatCloseTimer); floatCloseTimer = window.setTimeout(() => { floatPopup.value.visible = false; - }, 150); + }, 260); }; const cancelFloatClose = () => { @@ -608,67 +610,103 @@ const handleCitationActivate = (el: HTMLElement) => { const url = el.getAttribute('data-url'); if (!url) return; try { - window.open(url, '_blank', 'noopener,noreferrer'); + const newWindow = window.open(url, '_blank', 'noopener,noreferrer'); + if (!newWindow) { + window.location.assign(url); + } } catch { - // noop + window.location.assign(url); } }; // KB citations: 悬停用浮层展示摘要;点击跳转 KB 详情 -const kbChunkDetails = ref>({}); +type KbTooltipState = { + loading: boolean; + error?: string; + html?: string; +}; + +const kbChunkDetails = ref>({}); + +const escapeHtml = (value: string): string => + value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + +const buildKbTooltipContent = (content: string): string => { + const trimmed = content.length > KB_SNIPPET_LIMIT ? content.substring(0, KB_SNIPPET_LIMIT) + '...' : content; + const escapedContent = escapeHtml(trimmed).replace(/\n/g, '
'); + return `${escapedContent}`; +}; + +const getKbTooltipInnerHtml = (state: KbTooltipState): string => { + if (state.error) { + return `${escapeHtml(state.error)}`; + } + if (state.html) { + return state.html; + } + return `加载中...`; +}; + +const syncFloatPopupFromCache = (chunkId: string, state: KbTooltipState) => { + if (floatPopup.value.type !== 'kb' || floatPopup.value.chunkId !== chunkId) { + return; + } + floatPopup.value.loading = state.loading; + floatPopup.value.error = state.error; + floatPopup.value.content = state.html || ''; +}; + +const setKbCacheState = (chunkId: string, state: KbTooltipState) => { + kbChunkDetails.value[chunkId] = state; + updateKBCitationTooltip(chunkId, state); + syncFloatPopupFromCache(chunkId, state); +}; const loadChunkDetails = async (chunkId: string) => { - // Skip if already loaded or currently loading - if (kbChunkDetails.value[chunkId]) { - if (kbChunkDetails.value[chunkId].loading) { - return; // Already loading + const cacheEntry = kbChunkDetails.value[chunkId]; + if (cacheEntry) { + if (cacheEntry.loading) { + updateKBCitationTooltip(chunkId, cacheEntry); + syncFloatPopupFromCache(chunkId, cacheEntry); + return; } - if (kbChunkDetails.value[chunkId].content) { - // Already loaded, update tooltip immediately - updateKBCitationTooltip(chunkId, kbChunkDetails.value[chunkId].content); + if (cacheEntry.html || cacheEntry.error) { + updateKBCitationTooltip(chunkId, cacheEntry); + syncFloatPopupFromCache(chunkId, cacheEntry); return; } } - - // Set loading state - kbChunkDetails.value[chunkId] = { loading: true }; - updateKBCitationTooltip(chunkId); // Show loading state - + + setKbCacheState(chunkId, { loading: true }); + try { const response = await getChunkByIdOnly(chunkId); - if (response.data && response.data.content) { - kbChunkDetails.value[chunkId] = { - content: response.data.content, - loading: false - }; - // Update the tooltip content in the DOM - updateKBCitationTooltip(chunkId, response.data.content); - } else { - const errorMsg = '未找到内容'; - kbChunkDetails.value[chunkId] = { - loading: false, - error: errorMsg - }; - updateKBCitationTooltip(chunkId, undefined, errorMsg); + const content = response.data?.content; + if (content) { + const html = buildKbTooltipContent(content); + setKbCacheState(chunkId, { loading: false, html }); + return; } + + setKbCacheState(chunkId, { loading: false, error: '未找到内容' }); } catch (error: any) { console.error('Failed to load chunk details:', error); const errorMsg = error?.message || '加载失败'; - kbChunkDetails.value[chunkId] = { - loading: false, - error: errorMsg - }; - updateKBCitationTooltip(chunkId, undefined, errorMsg); + setKbCacheState(chunkId, { loading: false, error: errorMsg }); } }; -const updateKBCitationTooltip = (chunkId: string, content?: string, error?: string) => { +const updateKBCitationTooltip = (chunkId: string, state: KbTooltipState) => { // Find all KB citation elements with this chunk ID const citations = document.querySelectorAll(`.citation-kb[data-chunk-id="${chunkId}"]`); citations.forEach((citation) => { const tipElement = citation.querySelector('.citation-tip'); if (tipElement) { - const doc = citation.getAttribute('data-doc') || ''; const shortChunkId = `${chunkId.substring(0, 25)}...`; const renderContent = (inner: string) => { @@ -679,20 +717,8 @@ const updateKBCitationTooltip = (chunkId: string, content?: string, error?: stri `; }; - - if (error) { - renderContent(`${error}`); - } else if (content) { - const shortContent = content.length > 600 ? content.substring(0, 600) + '...' : content; - const escapedContent = shortContent - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/\n/g, '
'); - renderContent(`${escapedContent}`); - } else { - renderContent(`加载中...`); - } + + renderContent(getKbTooltipInnerHtml(state)); } }); }; @@ -710,13 +736,23 @@ const onHover = (e: Event) => { if (!chunkId) return; if (kbHoverTimer) window.clearTimeout(kbHoverTimer); kbHoverTimer = window.setTimeout(() => { + cancelFloatClose(); floatPopup.value.type = 'kb'; - floatPopup.value.loading = true; - floatPopup.value.error = undefined; - floatPopup.value.content = ''; floatPopup.value.chunkId = chunkId; + const cacheEntry = kbChunkDetails.value[chunkId]; + if (cacheEntry) { + syncFloatPopupFromCache(chunkId, cacheEntry); + updateKBCitationTooltip(chunkId, cacheEntry); + } else { + floatPopup.value.loading = true; + floatPopup.value.error = undefined; + floatPopup.value.content = ''; + } openFloatForEl(kbEl); - loadChunkDetails(chunkId); + + if (!cacheEntry || (!cacheEntry.loading && !cacheEntry.html && !cacheEntry.error)) { + loadChunkDetails(chunkId); + } }, 80); return; } @@ -754,8 +790,10 @@ const onRootClick = (e: Event) => { // Handle web citation clicks const webEl = target.closest?.('.citation-web') as HTMLElement | null; if (webEl && webEl.getAttribute('data-url')) { - e.preventDefault(); - handleCitationActivate(webEl); + if (!(webEl instanceof HTMLAnchorElement)) { + e.preventDefault(); + handleCitationActivate(webEl); + } return; } @@ -785,8 +823,15 @@ const onRootKeydown = (e: KeyboardEvent) => { const webEl = target.closest?.('.citation-web') as HTMLElement | null; if (webEl) { if (e.key === 'Enter' || e.key === ' ') { + if (webEl instanceof HTMLAnchorElement && e.key === 'Enter') { + return; + } e.preventDefault(); - handleCitationActivate(webEl); + if (webEl instanceof HTMLAnchorElement) { + webEl.click(); + } else { + handleCitationActivate(webEl); + } } return; } @@ -879,7 +924,7 @@ const renderMarkdown = (content: any): string => { const tipTitle = safeTitle || ''; const tipUrl = safeUrl || ''; // Keep lightweight tooltip (no t-popup container) to avoid global popup styling - return `${domain}${tipTitle}${tipUrl}`; + return `${domain}${tipTitle}${tipUrl}`; } ) // KB citations -> inline badges with simplified display @@ -1935,7 +1980,7 @@ const formatJSON = (obj: any): string => { } :deep(.citation .citation-tip) { - display: none !important; + display: none; } :deep(.citation-web) { @@ -1983,6 +2028,7 @@ const formatJSON = (obj: any): string => { display: block; font-weight: 600; /* bold title */ margin-bottom: 4px; + color: #07C05F; } :deep(.citation-web .citation-tip .tip-url) { @@ -2012,6 +2058,67 @@ const formatJSON = (obj: any): string => { background-image: url("../../../assets/img/zhishiku-thin.svg"); } +.kb-float-popup { + position: absolute; + z-index: 10000; + pointer-events: auto; + background: #f9fafb; + border-radius: 6px; + border: none !important; + box-shadow: 0 6px 18px rgba(0,0,0,0.2); + padding: 12px 14px; + color: #111827; + line-height: 1.5; + font-size: 12px; + box-sizing: border-box; + max-width: 520px; +} + +.kb-float-popup .t-popup__content { + display: flex; + flex-direction: column; + gap: 4px; + border: none !important; + padding: 0 !important; + margin: 0 !important; + background: transparent !important; + box-shadow: none !important; +} + +.kb-float-popup .tip-title { + font-weight: 600; + color: #065f46; +} + +.kb-float-popup .tip-url { + color: #2563eb; + word-break: break-word; +} + +.kb-float-popup .tip-meta { + margin-top: 8px; + font-size: 11px; + color: #6b7280; +} + +.kb-float-popup .tip-loading { + color: #6b7280; + font-style: italic; +} + +.kb-float-popup .tip-error { + color: #dc2626; + font-weight: 500; +} + +.kb-float-popup .tip-content { + border: none !important; + padding: 0 !important; + margin: 0 !important; + background: transparent !important; + box-shadow: none !important; +} + /* KB citation styles - same green theme as web citations */ :deep(.citation.citation-kb) { /* Green theme - same as web citations */ @@ -2038,99 +2145,8 @@ const formatJSON = (obj: any): string => { /* KB citation tooltip styles (same as web citation) */ :deep(.citation.citation-kb .citation-tip) { - display: none; - position: absolute; - left: 0; - top: 100%; /* 紧贴父元素底部,避免鼠标穿过空隙导致消失 */ - /* popup container mimic */ - z-index: 9999; - color: #111827; - background: transparent; /* 外层透明,避免顶部出现白边 */ - border-radius: 0; - padding: 8px 0 0; /* 仅用上内边距制造视觉间距,保持可 hover 区域连续 */ - font-size: 12px; - line-height: 1.5; - box-shadow: none; /* 阴影放到内部容器 */ - width: 420px; /* fixed width to avoid layout jump */ - min-height: 120px; /* reserve space to avoid jitter before content arrives */ - pointer-events: auto; /* 允许在弹层内部滚动与交互 */ - word-wrap: break-word; - overflow-wrap: break-word; - white-space: normal; -} - -:deep(.citation.citation-kb:hover .citation-tip) { - display: block; -} - -/* inner content mimic of t-popup__content */ -:deep(.citation.citation-kb .citation-tip .t-popup__content) { - display: block; - padding: 12px 14px; /* actual padding here */ - max-height: 340px; - overflow-y: auto; /* inner scroll */ - background: #f9fafb; /* 背景、圆角与阴影移动到内部容器 */ - border-radius: 6px; - box-shadow: 0 6px 18px rgba(0,0,0,0.2); - box-sizing: border-box; - overscroll-behavior: contain; /* 防止滚动穿透到页面 */ - -webkit-overflow-scrolling: touch; /* iOS 惯性滚动 */ -} - -:deep(.citation.citation-kb .citation-tip .tip-title) { - display: block; - font-weight: 600; - margin-bottom: 6px; - color: #065f46; /* green-800 to match citation */ -} - -:deep(.citation.citation-kb .citation-tip .tip-doc) { - display: block; - color: #111827; - margin-bottom: 8px; -} - -:deep(.citation.citation-kb .citation-tip .tip-content) { - display: block; - color: #374151; - line-height: 1.6; - max-height: 300px; - overflow-y: auto; - margin-top: 4px; - word-break: break-word; - white-space: normal; -} - -:deep(.citation.citation-kb .citation-tip .tip-content::-webkit-scrollbar) { - width: 6px; -} - -:deep(.citation.citation-kb .citation-tip .tip-content::-webkit-scrollbar-track) { - background: #f1f1f1; - border-radius: 3px; -} - -:deep(.citation.citation-kb .citation-tip .tip-content::-webkit-scrollbar-thumb) { - background: #888; - border-radius: 3px; -} - -:deep(.citation.citation-kb .citation-tip .tip-content::-webkit-scrollbar-thumb:hover) { - background: #555; -} - -:deep(.citation.citation-kb .citation-tip .tip-loading) { - display: block; - color: #6b7280; - font-style: italic; - font-size: 11px; -} - -:deep(.citation.citation-kb .citation-tip .tip-error) { - display: block; - color: #dc2626; - font-size: 11px; - margin-top: 4px; + display: none !important; + pointer-events: none; } .tool-arguments-wrapper { diff --git a/internal/agent/engine.go b/internal/agent/engine.go index ffc80753..e3e15ebf 100644 --- a/internal/agent/engine.go +++ b/internal/agent/engine.go @@ -376,12 +376,12 @@ func (e *AgentEngine) executeLoop( Type: event.EventAgentComplete, SessionID: sessionID, Data: event.AgentCompleteData{ - FinalAnswer: state.FinalAnswer, - KnowledgeRefs: knowledgeRefsInterface, - AgentSteps: state.RoundSteps, // Include detailed execution steps for message storage - TotalSteps: len(state.RoundSteps), - TotalDuration: time.Since(startTime).Milliseconds(), - MessageID: messageID, // Include message ID for proper message update + FinalAnswer: state.FinalAnswer, + KnowledgeRefs: knowledgeRefsInterface, + AgentSteps: state.RoundSteps, // Include detailed execution steps for message storage + TotalSteps: len(state.RoundSteps), + TotalDurationMs: time.Since(startTime).Milliseconds(), + MessageID: messageID, // Include message ID for proper message update }, }) diff --git a/internal/agent/prompts.go b/internal/agent/prompts.go index 917eec5c..bacb9a56 100644 --- a/internal/agent/prompts.go +++ b/internal/agent/prompts.go @@ -209,13 +209,19 @@ Your pretraining data may be outdated or incorrect. Do NOT rely on any internal -- Within the Answer section (not in intermediate tool steps), place citations inline near the content they support. Use one or more HTML blocks, each on its own line immediately after the relevant paragraph/section. Do NOT aggregate all citations at the end of the answer. +- Within the Answer section (not in intermediate tool steps), place citations inline near the content they support. Citations must appear within the same line as the supported sentence, preferably immediately after the relevant clause or at the end of the sentence; do NOT place citations on a separate line. Do NOT aggregate all citations at the end of the answer. Include only sources actually used in the answer. Item formats (compact attributes for easy parsing): - Knowledge Base: - Web Page: - Example: - Paragraph explaining concept A... - Paragraph summarizing current news... + Good Example: + Paragraph explaining concept A... ... + Statement supported by multiple sources... + + Bad Example: + Paragraph explaining concept A... + + Paragraph summarizing current news... + ` diff --git a/internal/event/event_data.go b/internal/event/event_data.go index 7564015b..4ad34ce1 100644 --- a/internal/event/event_data.go +++ b/internal/event/event_data.go @@ -135,15 +135,15 @@ type AgentQueryData struct { // AgentCompleteData represents agent completion event data type AgentCompleteData struct { - SessionID string `json:"session_id"` - TotalSteps int `json:"total_steps"` - FinalAnswer string `json:"final_answer"` - KnowledgeRefs []interface{} `json:"knowledge_refs,omitempty"` // []*types.SearchResult - AgentSteps interface{} `json:"agent_steps,omitempty"` // []types.AgentStep - detailed execution steps - TotalDuration int64 `json:"total_duration_ms"` - MessageID string `json:"message_id,omitempty"` // Assistant message ID - RequestID string `json:"request_id,omitempty"` - Extra map[string]interface{} `json:"extra,omitempty"` + SessionID string `json:"session_id"` + TotalSteps int `json:"total_steps"` + FinalAnswer string `json:"final_answer"` + KnowledgeRefs []interface{} `json:"knowledge_refs,omitempty"` // []*types.SearchResult + AgentSteps interface{} `json:"agent_steps,omitempty"` // []types.AgentStep - detailed execution steps + TotalDurationMs int64 `json:"total_duration_ms"` + MessageID string `json:"message_id,omitempty"` // Assistant message ID + RequestID string `json:"request_id,omitempty"` + Extra map[string]interface{} `json:"extra,omitempty"` } // === Streaming Event Data Structures === diff --git a/internal/handler/session/agent_stream_handler.go b/internal/handler/session/agent_stream_handler.go index bcf7eddc..477fd190 100644 --- a/internal/handler/session/agent_stream_handler.go +++ b/internal/handler/session/agent_stream_handler.go @@ -398,8 +398,8 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event Done: true, Timestamp: time.Now(), Data: map[string]interface{}{ - "total_steps": data.TotalSteps, - "total_duration": data.TotalDuration, + "total_steps": data.TotalSteps, + "total_duration_ms": data.TotalDurationMs, }, }); err != nil { logger.GetLogger(h.ctx).Error("Append complete event to stream failed", "error", err)