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)',
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',
+1
View File
@@ -283,6 +283,7 @@ export default {
referencesDocCount: "{count}개 문서 참조",
referencesDocAndWebCount: "{docCount}개 문서와 {webCount}개 웹페이지 참조",
referenceChunkCount: "{count}개 청크",
fallbackHint: "지식 베이스에서 관련 내용을 찾지 못했습니다. 위는 모델의 직접 응답입니다.",
chunkLabel: "청크 {index}:",
navigateToDocument: "문서 상세 보기",
referenceIconAlt: "참조 내용 아이콘",
+1
View File
@@ -1353,6 +1353,7 @@ export default {
referencesDocCount: 'Использовано {count} документ(ов)',
referencesDocAndWebCount: 'Использовано {docCount} документ(ов) и {webCount} веб-страниц(ы)',
referenceChunkCount: '{count} фрагмент(ов)',
fallbackHint: 'В базе знаний не найдено релевантного содержимого. Выше представлен прямой ответ модели.',
chunkLabel: 'Фрагмент {index}:',
navigateToDocument: 'Просмотр документа',
referenceIconAlt: 'Иконка ссылок на материалы',
+1
View File
@@ -285,6 +285,7 @@ export default {
referencesDocCount: "引用了{count}篇文档",
referencesDocAndWebCount: "引用了{docCount}篇文档和{webCount}条网页",
referenceChunkCount: "{count}个片段",
fallbackHint: "未从知识库中检索到相关内容,以上为模型直接回答",
chunkLabel: "片段{index}:",
navigateToDocument: "查看文档详情",
referenceIconAlt: "参考内容图标",
@@ -44,10 +44,10 @@
<!-- Answer Event -->
<div v-else-if="event.type === 'answer' && (event.done || (event.content && event.content.trim()))" class="answer-event">
<div
<div
v-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;
+79 -3
View File
@@ -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;
+23 -17
View File
@@ -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;
+26 -7
View File
@@ -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('<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;
+6 -4
View File
@@ -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)
+3 -2
View File
@@ -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
@@ -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)
+3
View File
@@ -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 {
+2
View File
@@ -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
+1
View File
@@ -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
@@ -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;