diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index abf12637..5fd8c9f0 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -1528,6 +1528,7 @@ export default { referencesDocCount: 'Referenced {count} document(s)', referencesDocAndWebCount: 'Referenced {docCount} document(s) and {webCount} web page(s)', referenceChunkCount: '{count} chunk(s)', + fallbackHint: 'No relevant content found in knowledge base. Above is a direct response from the model.', chunkLabel: 'Chunk {index}:', navigateToDocument: 'View document details', referenceIconAlt: 'Reference materials icon', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index bdcc4bdd..49997252 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -283,6 +283,7 @@ export default { referencesDocCount: "{count}개 문서 참조", referencesDocAndWebCount: "{docCount}개 문서와 {webCount}개 웹페이지 참조", referenceChunkCount: "{count}개 청크", + fallbackHint: "지식 베이스에서 관련 내용을 찾지 못했습니다. 위는 모델의 직접 응답입니다.", chunkLabel: "청크 {index}:", navigateToDocument: "문서 상세 보기", referenceIconAlt: "참조 내용 아이콘", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index fa630fc6..4f26511b 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -1353,6 +1353,7 @@ export default { referencesDocCount: 'Использовано {count} документ(ов)', referencesDocAndWebCount: 'Использовано {docCount} документ(ов) и {webCount} веб-страниц(ы)', referenceChunkCount: '{count} фрагмент(ов)', + fallbackHint: 'В базе знаний не найдено релевантного содержимого. Выше представлен прямой ответ модели.', chunkLabel: 'Фрагмент {index}:', navigateToDocument: 'Просмотр документа', referenceIconAlt: 'Иконка ссылок на материалы', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 37982771..5684024c 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -285,6 +285,7 @@ export default { referencesDocCount: "引用了{count}篇文档", referencesDocAndWebCount: "引用了{docCount}篇文档和{webCount}条网页", referenceChunkCount: "{count}个片段", + fallbackHint: "未从知识库中检索到相关内容,以上为模型直接回答", chunkLabel: "片段{index}:", navigateToDocument: "查看文档详情", referenceIconAlt: "参考内容图标", diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index 1f86876f..6d439a73 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -44,10 +44,10 @@
-
+ + + + + +
@@ -2026,7 +2032,17 @@ const handleAddToKnowledge = (answerEvent: any) => { .answer-event { animation: fadeInUp 0.25s ease-out; min-height: 20px; - + + .fallback-icon-btn { + color: #d1d5db !important; + border-color: #e5e7eb !important; + + &:hover { + color: #9ca3af !important; + border-color: #d1d5db !important; + } + } + .answer-content-wrapper { background: #ffffff; border-radius: 6px; diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue index f26eb74c..d50b4cba 100644 --- a/frontend/src/views/chat/components/botmsg.vue +++ b/frontend/src/views/chat/components/botmsg.vue @@ -3,9 +3,9 @@
- + + + + + +
{{ $t('common.loading') }}
@@ -135,6 +141,10 @@ customRenderer.image = function(href, title, text) { customRenderer.code = createMermaidCodeRenderer('mermaid-botmsg'); // 计算属性:将 Markdown 文本转换为 tokens +const mentionedItems = computed(() => { + return props.session?.mentioned_items || []; +}); + const markdownTokens = computed(() => { const text = props.content || props.session?.content || ''; if (!text || typeof text !== 'string') { @@ -305,6 +315,72 @@ onBeforeUnmount(() => { transition: all 0.2s ease; } +.mentioned_items { + display: flex; + flex-wrap: wrap; + gap: 6px; + justify-content: flex-start; + max-width: 100%; + margin-bottom: 2px; +} + +.mentioned_tag { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 3px 8px; + border-radius: 10px; + font-size: 12px; + font-weight: 500; + max-width: 200px; + cursor: default; + transition: all 0.15s; + background: rgba(7, 192, 95, 0.06); + border: 1px solid rgba(7, 192, 95, 0.2); + color: #374151; + + &.kb-tag { + .tag_icon { + color: #07c05f; + } + } + + &.faq-tag { + .tag_icon { + color: #f59e0b; + } + } + + &.file-tag { + .tag_icon { + color: #6b7280; + } + } + + .tag_icon { + font-size: 13px; + display: flex; + align-items: center; + } + + .tag_name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: currentColor; + } +} + +.fallback-icon-btn { + color: #d1d5db !important; + border-color: #e5e7eb !important; + + &:hover { + color: #9ca3af !important; + border-color: #d1d5db !important; + } +} + @keyframes fadeInUp { from { opacity: 0; diff --git a/frontend/src/views/chat/components/usermsg.vue b/frontend/src/views/chat/components/usermsg.vue index a5c4d1b1..c25f1fe9 100644 --- a/frontend/src/views/chat/components/usermsg.vue +++ b/frontend/src/views/chat/components/usermsg.vue @@ -61,35 +61,41 @@ const props = defineProps({ display: inline-flex; align-items: center; gap: 4px; - padding: 4px 8px; - border-radius: 6px; + padding: 3px 8px; + border-radius: 10px; font-size: 12px; font-weight: 500; max-width: 200px; cursor: default; transition: all 0.15s; - background: var(--td-bg-color-secondarycontainer, #f3f3f3); - border: 1px solid transparent; - color: var(--td-text-color-primary, #333); - - /* 知识库 / 文件 - 无背景,与整体一致 */ - &.kb-tag, - &.faq-tag, - &.file-tag { - background: transparent; - color: var(--td-text-color-primary, #333); - + background: rgba(7, 192, 95, 0.06); + border: 1px solid rgba(7, 192, 95, 0.2); + color: #374151; + + &.kb-tag { .tag_icon { - color: var(--td-text-color-secondary, #666); + color: #07c05f; } } - + + &.faq-tag { + .tag_icon { + color: #f59e0b; + } + } + + &.file-tag { + .tag_icon { + color: #6b7280; + } + } + .tag_icon { - font-size: 14px; + font-size: 13px; display: flex; align-items: center; } - + .tag_name { overflow: hidden; text-overflow: ellipsis; diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue index 2c6380b8..5bc64de7 100644 --- a/frontend/src/views/chat/index.vue +++ b/frontend/src/views/chat/index.vue @@ -156,9 +156,9 @@ const getmsgList = (data, isScrollType = false, scrollHeight) => { // Reconstruct agentEventStream from agent_steps stored in database // This allows the frontend to restore the exact conversation state including all agent reasoning steps -const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted = false) => { +const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted = false, isFallback = false) => { const events = []; - + // Process agent steps if they exist if (agentSteps && Array.isArray(agentSteps) && agentSteps.length > 0) { agentSteps.forEach((step) => { @@ -201,19 +201,23 @@ const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted // 总是添加 answer 事件如果有内容(无论是否有 agent_steps) // 这样可以确保最终答案始终被渲染 if (messageContent && messageContent.trim()) { - events.push({ + const answerEvent = { type: 'answer', content: messageContent, done: true - }); + }; + if (isFallback) answerEvent.is_fallback = true; + events.push(answerEvent); } else if (isCompleted) { // 如果消息已完成但 content 为空(Agent 模式常见情况),添加一个空的 answer 事件标记完成 // 这样可以确保 isConversationDone 返回 true,不显示 loading-indicator - events.push({ + const answerEvent = { type: 'answer', content: '', done: true - }); + }; + if (isFallback) answerEvent.is_fallback = true; + events.push(answerEvent); } return events; @@ -232,7 +236,7 @@ const handleMsgList = async (data, isScrollType = false, newScrollHeight) => { if (item.agent_steps && Array.isArray(item.agent_steps) && item.agent_steps.length > 0) { console.log('[Message Load] Reconstructing agent steps for message:', item.id, 'steps:', item.agent_steps.length); item.isAgentMode = true; - item.agentEventStream = reconstructEventStreamFromSteps(item.agent_steps, item.content, item.is_completed); + item.agentEventStream = reconstructEventStreamFromSteps(item.agent_steps, item.content, item.is_completed, item.is_fallback); // 隐藏最终答案内容,因为它已经包含在 agentEventStream 的 answer 事件中 item.hideContent = true; console.log('[Message Load] Reconstructed', item.agentEventStream.length, 'events from agent steps'); @@ -516,6 +520,11 @@ onChunk((data) => { fullContent.value += data.content; let obj = { ...data, content: '', role: 'assistant', showThink: false, is_completed: false }; + // 检查是否为 fallback 回答(未从知识库检索到内容) + if (data.data?.is_fallback) { + obj.is_fallback = true; + } + if (fullContent.value.includes('') && !fullContent.value.includes('<\/think>')) { obj.thinking = true; obj.showThink = true; @@ -811,6 +820,12 @@ const handleAgentChunk = (data) => { answerEvent.content = message.content; console.log('[Answer] answerEvent.content updated, length:', answerEvent.content.length); } + + // 检查是否为 fallback 回答 + if (data.data?.is_fallback) { + answerEvent.is_fallback = true; + message.is_fallback = true; + } // 只在第一次收到 done:true 时标记完成,忽略后续重复的完成事件 if (data.done && !answerEvent.done) { @@ -873,6 +888,10 @@ const updateAssistantSession = (payload) => { message.thinkContent = payload.thinkContent; message.showThink = payload.showThink; message.knowledge_references = message.knowledge_references ? message.knowledge_references : payload.knowledge_references; + // 更新 fallback 状态 + if (payload.is_fallback) { + message.is_fallback = true; + } // 更新完成状态 if (payload.is_completed) { message.is_completed = true; diff --git a/internal/application/service/session.go b/internal/application/service/session.go index 527ae5a6..04d17b01 100644 --- a/internal/application/service/session.go +++ b/internal/application/service/session.go @@ -1709,8 +1709,9 @@ func (s *sessionService) consumeFallbackStream( Type: types.EventType(event.EventAgentFinalAnswer), SessionID: chatManage.SessionID, Data: event.AgentFinalAnswerData{ - Content: response.Content, - Done: response.Done, + Content: response.Content, + Done: response.Done, + IsFallback: true, }, }); err != nil { logger.Errorf(ctx, "Failed to emit fallback answer chunk event: %v", err) @@ -1745,8 +1746,9 @@ func (s *sessionService) emitFallbackAnswer(ctx context.Context, chatManage *typ Type: types.EventType(event.EventAgentFinalAnswer), SessionID: chatManage.SessionID, Data: event.AgentFinalAnswerData{ - Content: content, - Done: true, + Content: content, + Done: true, + IsFallback: true, }, }); err != nil { logger.Errorf(ctx, "Failed to emit fallback answer event: %v", err) diff --git a/internal/event/event_data.go b/internal/event/event_data.go index a8b3f03d..d7a299c6 100644 --- a/internal/event/event_data.go +++ b/internal/event/event_data.go @@ -183,8 +183,9 @@ type AgentReferencesData struct { // AgentFinalAnswerData represents final answer streaming data type AgentFinalAnswerData struct { - Content string `json:"content"` - Done bool `json:"done"` + Content string `json:"content"` + Done bool `json:"done"` + IsFallback bool `json:"is_fallback,omitempty"` // True when response is a fallback (no knowledge base match) } // AgentReflectionData represents agent reflection data diff --git a/internal/handler/session/agent_stream_handler.go b/internal/handler/session/agent_stream_handler.go index 72bee047..399ca4ab 100644 --- a/internal/handler/session/agent_stream_handler.go +++ b/internal/handler/session/agent_stream_handler.go @@ -291,6 +291,9 @@ func (h *AgentStreamHandler) handleFinalAnswer(ctx context.Context, evt event.Ev // Accumulate final answer locally for assistant message (database) h.finalAnswer += data.Content + if data.IsFallback { + h.assistantMessage.IsFallback = true + } // Calculate duration if done var metadata map[string]interface{} @@ -308,6 +311,9 @@ func (h *AgentStreamHandler) handleFinalAnswer(ctx context.Context, evt event.Ev "event_id": evt.ID, } } + if data.IsFallback { + metadata["is_fallback"] = true + } h.mu.Unlock() // Append this chunk to stream (frontend will accumulate by event ID) diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index 617648a1..fd12983a 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -406,6 +406,9 @@ func (h *Handler) executeNormalModeQA(reqCtx *qaRequestContext, generateTitle bo return nil } streamCtx.assistantMessage.Content += data.Content + if data.IsFallback { + streamCtx.assistantMessage.IsFallback = true + } if data.Done { // Prevent duplicate completion handling if completionHandled { diff --git a/internal/types/message.go b/internal/types/message.go index ecef2077..c664afd9 100644 --- a/internal/types/message.go +++ b/internal/types/message.go @@ -78,6 +78,8 @@ type Message struct { MentionedItems MentionedItems `json:"mentioned_items,omitempty" gorm:"type:jsonb,column:mentioned_items"` // Whether message generation is complete IsCompleted bool `json:"is_completed"` + // Whether this response is a fallback (no knowledge base match found) + IsFallback bool `json:"is_fallback,omitempty"` // Message creation timestamp CreatedAt time.Time `json:"created_at"` // Last update timestamp diff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sql index 101f7506..a61a12a9 100644 --- a/migrations/sqlite/000000_init.up.sql +++ b/migrations/sqlite/000000_init.up.sql @@ -142,6 +142,7 @@ CREATE TABLE IF NOT EXISTS messages ( agent_steps TEXT DEFAULT NULL, mentioned_items TEXT DEFAULT '[]', is_completed BOOLEAN NOT NULL DEFAULT 0, + is_fallback BOOLEAN NOT NULL DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, deleted_at DATETIME diff --git a/migrations/versioned/000015_add_is_fallback.down.sql b/migrations/versioned/000015_add_is_fallback.down.sql new file mode 100644 index 00000000..aedbe58a --- /dev/null +++ b/migrations/versioned/000015_add_is_fallback.down.sql @@ -0,0 +1,2 @@ +-- Remove is_fallback column from messages table +ALTER TABLE messages DROP COLUMN IF EXISTS is_fallback; diff --git a/migrations/versioned/000015_add_is_fallback.up.sql b/migrations/versioned/000015_add_is_fallback.up.sql new file mode 100644 index 00000000..efb6bd84 --- /dev/null +++ b/migrations/versioned/000015_add_is_fallback.up.sql @@ -0,0 +1,3 @@ +-- Add is_fallback column to messages table +-- Tracks whether a response was generated using fallback logic (no knowledge base match found) +ALTER TABLE messages ADD COLUMN IF NOT EXISTS is_fallback BOOLEAN DEFAULT FALSE;