feat: add fallback response handling and UI indicators

- Introduced a new `is_fallback` property to track when responses are generated without knowledge base matches.
- Updated the chat components to display fallback hints and indicators in the UI, enhancing user awareness of fallback responses.
- Added translations for fallback hints in multiple languages, improving accessibility for diverse users.
- Modified backend logic to emit fallback status in response events, ensuring consistent handling across the application.

These changes improve the user experience by providing clear feedback on fallback responses, enhancing the overall interaction with the chat system.
This commit is contained in:
wizardchen
2026-03-04 21:32:19 +08:00
committed by lyingbug
parent 5ae076e22c
commit 44f38ca6c3
16 changed files with 177 additions and 36 deletions
+1
View File
@@ -1528,6 +1528,7 @@ export default {
referencesDocCount: 'Referenced {count} document(s)', referencesDocCount: 'Referenced {count} document(s)',
referencesDocAndWebCount: 'Referenced {docCount} document(s) and {webCount} web page(s)', referencesDocAndWebCount: 'Referenced {docCount} document(s) and {webCount} web page(s)',
referenceChunkCount: '{count} chunk(s)', referenceChunkCount: '{count} chunk(s)',
fallbackHint: 'No relevant content found in knowledge base. Above is a direct response from the model.',
chunkLabel: 'Chunk {index}:', chunkLabel: 'Chunk {index}:',
navigateToDocument: 'View document details', navigateToDocument: 'View document details',
referenceIconAlt: 'Reference materials icon', referenceIconAlt: 'Reference materials icon',
+1
View File
@@ -283,6 +283,7 @@ export default {
referencesDocCount: "{count}개 문서 참조", referencesDocCount: "{count}개 문서 참조",
referencesDocAndWebCount: "{docCount}개 문서와 {webCount}개 웹페이지 참조", referencesDocAndWebCount: "{docCount}개 문서와 {webCount}개 웹페이지 참조",
referenceChunkCount: "{count}개 청크", referenceChunkCount: "{count}개 청크",
fallbackHint: "지식 베이스에서 관련 내용을 찾지 못했습니다. 위는 모델의 직접 응답입니다.",
chunkLabel: "청크 {index}:", chunkLabel: "청크 {index}:",
navigateToDocument: "문서 상세 보기", navigateToDocument: "문서 상세 보기",
referenceIconAlt: "참조 내용 아이콘", referenceIconAlt: "참조 내용 아이콘",
+1
View File
@@ -1353,6 +1353,7 @@ export default {
referencesDocCount: 'Использовано {count} документ(ов)', referencesDocCount: 'Использовано {count} документ(ов)',
referencesDocAndWebCount: 'Использовано {docCount} документ(ов) и {webCount} веб-страниц(ы)', referencesDocAndWebCount: 'Использовано {docCount} документ(ов) и {webCount} веб-страниц(ы)',
referenceChunkCount: '{count} фрагмент(ов)', referenceChunkCount: '{count} фрагмент(ов)',
fallbackHint: 'В базе знаний не найдено релевантного содержимого. Выше представлен прямой ответ модели.',
chunkLabel: 'Фрагмент {index}:', chunkLabel: 'Фрагмент {index}:',
navigateToDocument: 'Просмотр документа', navigateToDocument: 'Просмотр документа',
referenceIconAlt: 'Иконка ссылок на материалы', referenceIconAlt: 'Иконка ссылок на материалы',
+1
View File
@@ -285,6 +285,7 @@ export default {
referencesDocCount: "引用了{count}篇文档", referencesDocCount: "引用了{count}篇文档",
referencesDocAndWebCount: "引用了{docCount}篇文档和{webCount}条网页", referencesDocAndWebCount: "引用了{docCount}篇文档和{webCount}条网页",
referenceChunkCount: "{count}个片段", referenceChunkCount: "{count}个片段",
fallbackHint: "未从知识库中检索到相关内容,以上为模型直接回答",
chunkLabel: "片段{index}:", chunkLabel: "片段{index}:",
navigateToDocument: "查看文档详情", navigateToDocument: "查看文档详情",
referenceIconAlt: "参考内容图标", referenceIconAlt: "参考内容图标",
@@ -63,6 +63,12 @@
<t-button size="small" variant="outline" shape="round" @click.stop="handleAddToKnowledge(event)" :title="$t('agent.addToKnowledgeBase')"> <t-button size="small" variant="outline" shape="round" @click.stop="handleAddToKnowledge(event)" :title="$t('agent.addToKnowledgeBase')">
<t-icon name="add" /> <t-icon name="add" />
</t-button> </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>
</div> </div>
@@ -2027,6 +2033,16 @@ const handleAddToKnowledge = (answerEvent: any) => {
animation: fadeInUp 0.25s ease-out; animation: fadeInUp 0.25s ease-out;
min-height: 20px; min-height: 20px;
.fallback-icon-btn {
color: #d1d5db !important;
border-color: #e5e7eb !important;
&:hover {
color: #9ca3af !important;
border-color: #d1d5db !important;
}
}
.answer-content-wrapper { .answer-content-wrapper {
background: #ffffff; background: #ffffff;
border-radius: 6px; border-radius: 6px;
@@ -39,6 +39,12 @@
<t-button size="small" variant="outline" shape="round" @click.stop="handleAddToKnowledge" :title="$t('agent.addToKnowledgeBase')"> <t-button size="small" variant="outline" shape="round" @click.stop="handleAddToKnowledge" :title="$t('agent.addToKnowledgeBase')">
<t-icon name="add" /> <t-icon name="add" />
</t-button> </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>
<div v-if="isImgLoading" class="img_loading"><t-loading size="small"></t-loading><span>{{ $t('common.loading') }}</span></div> <div v-if="isImgLoading" class="img_loading"><t-loading size="small"></t-loading><span>{{ $t('common.loading') }}</span></div>
</div> </div>
@@ -135,6 +141,10 @@ customRenderer.image = function(href, title, text) {
customRenderer.code = createMermaidCodeRenderer('mermaid-botmsg'); customRenderer.code = createMermaidCodeRenderer('mermaid-botmsg');
// 计算属性:将 Markdown 文本转换为 tokens // 计算属性:将 Markdown 文本转换为 tokens
const mentionedItems = computed(() => {
return props.session?.mentioned_items || [];
});
const markdownTokens = computed(() => { const markdownTokens = computed(() => {
const text = props.content || props.session?.content || ''; const text = props.content || props.session?.content || '';
if (!text || typeof text !== 'string') { if (!text || typeof text !== 'string') {
@@ -305,6 +315,72 @@ onBeforeUnmount(() => {
transition: all 0.2s ease; 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 { @keyframes fadeInUp {
from { from {
opacity: 0; opacity: 0;
+20 -14
View File
@@ -61,31 +61,37 @@ const props = defineProps({
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 4px; gap: 4px;
padding: 4px 8px; padding: 3px 8px;
border-radius: 6px; border-radius: 10px;
font-size: 12px; font-size: 12px;
font-weight: 500; font-weight: 500;
max-width: 200px; max-width: 200px;
cursor: default; cursor: default;
transition: all 0.15s; transition: all 0.15s;
background: var(--td-bg-color-secondarycontainer, #f3f3f3); background: rgba(7, 192, 95, 0.06);
border: 1px solid transparent; border: 1px solid rgba(7, 192, 95, 0.2);
color: var(--td-text-color-primary, #333); color: #374151;
/* 知识库 / 文件 - 无背景,与整体一致 */
&.kb-tag,
&.faq-tag,
&.file-tag {
background: transparent;
color: var(--td-text-color-primary, #333);
&.kb-tag {
.tag_icon { .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 { .tag_icon {
font-size: 14px; font-size: 13px;
display: flex; display: flex;
align-items: center; align-items: center;
} }
+25 -6
View File
@@ -156,7 +156,7 @@ const getmsgList = (data, isScrollType = false, scrollHeight) => {
// Reconstruct agentEventStream from agent_steps stored in database // Reconstruct agentEventStream from agent_steps stored in database
// This allows the frontend to restore the exact conversation state including all agent reasoning steps // 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 = []; const events = [];
// Process agent steps if they exist // Process agent steps if they exist
@@ -201,19 +201,23 @@ const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted
// 总是添加 answer 事件如果有内容(无论是否有 agent_steps) // 总是添加 answer 事件如果有内容(无论是否有 agent_steps)
// 这样可以确保最终答案始终被渲染 // 这样可以确保最终答案始终被渲染
if (messageContent && messageContent.trim()) { if (messageContent && messageContent.trim()) {
events.push({ const answerEvent = {
type: 'answer', type: 'answer',
content: messageContent, content: messageContent,
done: true done: true
}); };
if (isFallback) answerEvent.is_fallback = true;
events.push(answerEvent);
} else if (isCompleted) { } else if (isCompleted) {
// 如果消息已完成但 content 为空(Agent 模式常见情况),添加一个空的 answer 事件标记完成 // 如果消息已完成但 content 为空(Agent 模式常见情况),添加一个空的 answer 事件标记完成
// 这样可以确保 isConversationDone 返回 true,不显示 loading-indicator // 这样可以确保 isConversationDone 返回 true,不显示 loading-indicator
events.push({ const answerEvent = {
type: 'answer', type: 'answer',
content: '', content: '',
done: true done: true
}); };
if (isFallback) answerEvent.is_fallback = true;
events.push(answerEvent);
} }
return events; 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) { 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); console.log('[Message Load] Reconstructing agent steps for message:', item.id, 'steps:', item.agent_steps.length);
item.isAgentMode = true; 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 事件中 // 隐藏最终答案内容,因为它已经包含在 agentEventStream 的 answer 事件中
item.hideContent = true; item.hideContent = true;
console.log('[Message Load] Reconstructed', item.agentEventStream.length, 'events from agent steps'); console.log('[Message Load] Reconstructed', item.agentEventStream.length, 'events from agent steps');
@@ -516,6 +520,11 @@ onChunk((data) => {
fullContent.value += data.content; fullContent.value += data.content;
let obj = { ...data, content: '', role: 'assistant', showThink: false, is_completed: false }; 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>')) { if (fullContent.value.includes('<think>') && !fullContent.value.includes('<\/think>')) {
obj.thinking = true; obj.thinking = true;
obj.showThink = true; obj.showThink = true;
@@ -812,6 +821,12 @@ const handleAgentChunk = (data) => {
console.log('[Answer] answerEvent.content updated, length:', answerEvent.content.length); 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 时标记完成,忽略后续重复的完成事件 // 只在第一次收到 done:true 时标记完成,忽略后续重复的完成事件
if (data.done && !answerEvent.done) { if (data.done && !answerEvent.done) {
answerEvent.done = true; answerEvent.done = true;
@@ -873,6 +888,10 @@ const updateAssistantSession = (payload) => {
message.thinkContent = payload.thinkContent; message.thinkContent = payload.thinkContent;
message.showThink = payload.showThink; message.showThink = payload.showThink;
message.knowledge_references = message.knowledge_references ? message.knowledge_references : payload.knowledge_references; 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) { if (payload.is_completed) {
message.is_completed = true; message.is_completed = true;
+6 -4
View File
@@ -1709,8 +1709,9 @@ func (s *sessionService) consumeFallbackStream(
Type: types.EventType(event.EventAgentFinalAnswer), Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID, SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{ Data: event.AgentFinalAnswerData{
Content: response.Content, Content: response.Content,
Done: response.Done, Done: response.Done,
IsFallback: true,
}, },
}); err != nil { }); err != nil {
logger.Errorf(ctx, "Failed to emit fallback answer chunk event: %v", err) 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), Type: types.EventType(event.EventAgentFinalAnswer),
SessionID: chatManage.SessionID, SessionID: chatManage.SessionID,
Data: event.AgentFinalAnswerData{ Data: event.AgentFinalAnswerData{
Content: content, Content: content,
Done: true, Done: true,
IsFallback: true,
}, },
}); err != nil { }); err != nil {
logger.Errorf(ctx, "Failed to emit fallback answer event: %v", err) logger.Errorf(ctx, "Failed to emit fallback answer event: %v", err)
+3 -2
View File
@@ -183,8 +183,9 @@ type AgentReferencesData struct {
// AgentFinalAnswerData represents final answer streaming data // AgentFinalAnswerData represents final answer streaming data
type AgentFinalAnswerData struct { type AgentFinalAnswerData struct {
Content string `json:"content"` Content string `json:"content"`
Done bool `json:"done"` 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 // AgentReflectionData represents agent reflection data
@@ -291,6 +291,9 @@ func (h *AgentStreamHandler) handleFinalAnswer(ctx context.Context, evt event.Ev
// Accumulate final answer locally for assistant message (database) // Accumulate final answer locally for assistant message (database)
h.finalAnswer += data.Content h.finalAnswer += data.Content
if data.IsFallback {
h.assistantMessage.IsFallback = true
}
// Calculate duration if done // Calculate duration if done
var metadata map[string]interface{} var metadata map[string]interface{}
@@ -308,6 +311,9 @@ func (h *AgentStreamHandler) handleFinalAnswer(ctx context.Context, evt event.Ev
"event_id": evt.ID, "event_id": evt.ID,
} }
} }
if data.IsFallback {
metadata["is_fallback"] = true
}
h.mu.Unlock() h.mu.Unlock()
// Append this chunk to stream (frontend will accumulate by event ID) // Append this chunk to stream (frontend will accumulate by event ID)
+3
View File
@@ -406,6 +406,9 @@ func (h *Handler) executeNormalModeQA(reqCtx *qaRequestContext, generateTitle bo
return nil return nil
} }
streamCtx.assistantMessage.Content += data.Content streamCtx.assistantMessage.Content += data.Content
if data.IsFallback {
streamCtx.assistantMessage.IsFallback = true
}
if data.Done { if data.Done {
// Prevent duplicate completion handling // Prevent duplicate completion handling
if completionHandled { if completionHandled {
+2
View File
@@ -78,6 +78,8 @@ type Message struct {
MentionedItems MentionedItems `json:"mentioned_items,omitempty" gorm:"type:jsonb,column:mentioned_items"` MentionedItems MentionedItems `json:"mentioned_items,omitempty" gorm:"type:jsonb,column:mentioned_items"`
// Whether message generation is complete // Whether message generation is complete
IsCompleted bool `json:"is_completed"` 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 // Message creation timestamp
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
// Last update timestamp // Last update timestamp
+1
View File
@@ -142,6 +142,7 @@ CREATE TABLE IF NOT EXISTS messages (
agent_steps TEXT DEFAULT NULL, agent_steps TEXT DEFAULT NULL,
mentioned_items TEXT DEFAULT '[]', mentioned_items TEXT DEFAULT '[]',
is_completed BOOLEAN NOT NULL DEFAULT 0, is_completed BOOLEAN NOT NULL DEFAULT 0,
is_fallback BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME deleted_at DATETIME
@@ -0,0 +1,2 @@
-- Remove is_fallback column from messages table
ALTER TABLE messages DROP COLUMN IF EXISTS is_fallback;
@@ -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;