Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat: add fallback response handling and UI indicators
wizardchen44f38ca6c333
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex abf126375..5fd8c9f0a 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.tsindex bdcc4bddd..499972529 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.tsindex fa630fc67..4f26511b8 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.tsindex 37982771d..5684024c3 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.vueindex 1f86876f0..6d439a73f 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -44,10 +44,10 @@<!-- Answer Event --><div v-else-if="event.type === 'answer' && (event.done || (event.content && event.content.trim()))" class="answer-event">- <div+ <divv-if="event.content && event.content.trim()"class="answer-content-wrapper"- :class="{+ :class="{'answer-active': !event.done,'answer-done': event.done}"@@ -63,6 +63,12 @@<t-button size="small" variant="outline" shape="round" @click.stop="handleAddToKnowledge(event)" :title="$t('agent.addToKnowledgeBase')"><t-icon name="add" /></t-button>+ <!-- Fallback 提示图标 -->+ <t-tooltip v-if="event.is_fallback" :content="$t('chat.fallbackHint')" placement="top">+ <t-button size="small" variant="outline" shape="round" class="fallback-icon-btn">+ <t-icon name="info-circle" />+ </t-button>+ </t-tooltip></div></div>@@ -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.vueindex f26eb74c0..d50b4cba0 100644--- a/frontend/src/views/chat/components/botmsg.vue+++ b/frontend/src/views/chat/components/botmsg.vue@@ -3,9 +3,9 @@<div style="display: flex;flex-direction: column; gap:8px"><!-- 显示@的知识库和文件(非 Agent 模式下显示) --><div v-if="!session.isAgentMode && mentionedItems && mentionedItems.length > 0" class="mentioned_items">- <span- v-for="item in mentionedItems"- :key="item.id"+ <span+ v-for="item in mentionedItems"+ :key="item.id"class="mentioned_tag":class="[item.type === 'kb' ? (item.kb_type === 'faq' ? 'faq-tag' : 'kb-tag') : 'file-tag'@@ -39,6 +39,12 @@<t-button size="small" variant="outline" shape="round" @click.stop="handleAddToKnowledge" :title="$t('agent.addToKnowledgeBase')"><t-icon name="add" /></t-button>+ <!-- Fallback 提示图标 -->+ <t-tooltip v-if="session.is_fallback" :content="$t('chat.fallbackHint')" placement="top">+ <t-button size="small" variant="outline" shape="round" class="fallback-icon-btn">+ <t-icon name="info-circle" />+ </t-button>+ </t-tooltip></div><div v-if="isImgLoading" class="img_loading"><t-loading size="small"></t-loading><span>{{ $t('common.loading') }}</span></div></div>@@ -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.vueindex a5c4d1b13..c25f1fe9f 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,+ 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 {- background: transparent;- color: var(--td-text-color-primary, #333);-.tag_icon {- color: var(--td-text-color-secondary, #666);+ 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.vueindex 2c6380b81..5bc64de71 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 existif (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('<think>') && !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.goindex 527ae5a6f..04d17b01f 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 *typType: 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.goindex a8b3f03da..d7a299c6e 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 datatype 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 datadiff --git a/internal/handler/session/agent_stream_handler.go b/internal/handler/session/agent_stream_handler.goindex 72bee0474..399ca4abd 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 donevar 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.goindex 617648a11..fd12983a6 100644--- a/internal/handler/session/qa.go+++ b/internal/handler/session/qa.go@@ -406,6 +406,9 @@ func (h *Handler) executeNormalModeQA(reqCtx *qaRequestContext, generateTitle boreturn nil}streamCtx.assistantMessage.Content += data.Content+ if data.IsFallback {+ streamCtx.assistantMessage.IsFallback = true+ }if data.Done {// Prevent duplicate completion handlingif completionHandled {diff --git a/internal/types/message.go b/internal/types/message.goindex ecef2077b..c664afd9e 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 completeIsCompleted bool `json:"is_completed"`+ // Whether this response is a fallback (no knowledge base match found)+ IsFallback bool `json:"is_fallback,omitempty"`// Message creation timestampCreatedAt time.Time `json:"created_at"`// Last update timestampdiff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sqlindex 101f7506e..a61a12a9b 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 DATETIMEdiff --git a/migrations/versioned/000015_add_is_fallback.down.sql b/migrations/versioned/000015_add_is_fallback.down.sqlnew file mode 100644index 000000000..aedbe58a2--- /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.sqlnew file mode 100644index 000000000..efb6bd842--- /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;