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
fix(chat): 兜底回答不再把原始命中数报成检索结果数
wizardchen49010d2526a0
diff --git a/frontend/src/i18n/embed.ts b/frontend/src/i18n/embed.tsindex e01c0c10e..a0162bf98 100644--- a/frontend/src/i18n/embed.ts+++ b/frontend/src/i18n/embed.ts@@ -369,6 +369,7 @@ const messages = {},"search": {"noResults": "未找到匹配的内容",+ "candidatesBelowThreshold": "命中 {count} 条候选,相关性不足,未用于回答","foundResultsFromFiles": "找到 {count} 个结果,来自 {files} 个文件","foundResults": "找到 {count} 个结果","foundMixedResults": "找到 {count} 个结果({docCount} 篇文档,{webCount} 条网页)",@@ -865,6 +866,7 @@ const messages = {},"search": {"noResults": "No matching content found",+ "candidatesBelowThreshold": "Matched {count} candidate(s), none relevant enough to use","foundResultsFromFiles": "Found {count} result(s) from {files} file(s)","foundResults": "Found {count} result(s)","foundMixedResults": "Found {count} result(s) ({docCount} documents, {webCount} web results)",diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex d3d05d871..37e870ae2 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -5085,6 +5085,7 @@ export default {},search: {noResults: 'No matching content found',+ candidatesBelowThreshold: 'Matched {count} candidate(s), none relevant enough to use',foundResultsFromFiles: 'Found {count} result(s) from {files} file(s)',foundResults: 'Found {count} result(s)',foundMixedResults: 'Found {count} result(s) ({docCount} documents, {webCount} web results)',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 7057faa89..6fbf69d98 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -1262,6 +1262,7 @@ export default {},search: {noResults: '일치하는 내용을 찾을 수 없습니다',+ candidatesBelowThreshold: '후보 {count}개를 찾았지만 관련성이 부족해 답변에 사용하지 않았습니다',foundResultsFromFiles: '{files}개 파일에서 {count}개 결과 발견',foundResults: '{count}개 결과 발견',foundMixedResults: '{count}개 결과 발견 ({docCount}개 문서, {webCount}개 웹)',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex ec6ceb999..228b28df5 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -1262,6 +1262,7 @@ export default {},search: {noResults: 'Совпадения не найдены',+ candidatesBelowThreshold: 'Найдено кандидатов: {count}, ни один не подошёл по релевантности',foundResultsFromFiles: 'Найдено {count} результат(ов) из {files} файл(ов)',foundResults: 'Найдено {count} результат(ов)',foundMixedResults: 'Найдено {count} результат(ов) ({docCount} док., {webCount} веб)',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 57b8cf137..d3d9a1b9a 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -1264,6 +1264,7 @@ export default {},search: {noResults: '未找到匹配的内容',+ candidatesBelowThreshold: '命中 {count} 条候选,相关性不足,未用于回答',foundResultsFromFiles: '找到 {count} 个结果,来自 {files} 个文件',foundResults: '找到 {count} 个结果',foundMixedResults: '找到 {count} 个结果({docCount} 篇文档,{webCount} 条网页)',diff --git a/frontend/src/utils/agent-tool-display.test.mjs b/frontend/src/utils/agent-tool-display.test.mjsindex b71790300..7e072c42d 100644--- a/frontend/src/utils/agent-tool-display.test.mjs+++ b/frontend/src/utils/agent-tool-display.test.mjs@@ -12,6 +12,9 @@ const t = (key, params) => {if (key === 'agentStream.search.foundResultsFromFiles') {return `found ${params?.count} from ${params?.files} files`}+ if (key === 'agentStream.search.candidatesBelowThreshold') {+ return `matched ${params?.count}, none relevant`+ }if (key === 'agentStream.ragPipeline.searchingWithQuery') {return `searching ${params?.query}`}@@ -58,6 +61,20 @@ test('getKnowledgeSearchSummaryHtml includes file count when present', () => {assert.match(html, /found <strong>2<\/strong> from <strong>2<\/strong> files/)})+// Candidates that all fell below the relevance threshold never reached the+// answer, so the row must not read like a plain empty search: the difference+// points at the threshold rather than at the knowledge base.+test('getKnowledgeSearchSummaryHtml distinguishes filtered candidates from an empty search', () => {+ assert.match(+ getKnowledgeSearchSummaryHtml(t, { count: 0, candidate_count: 10 }),+ /matched <strong>10<\/strong>, none relevant/,+ )+ assert.equal(+ getKnowledgeSearchSummaryHtml(t, { count: 0, candidate_count: 0 }),+ 'agentStream.search.noResults',+ )+})+test('getRagPipelineStepTitle uses query-aware search labels', () => {const title = getRagPipelineStepTitle(t, {tool_name: 'knowledge_search',diff --git a/frontend/src/utils/agent-tool-display.ts b/frontend/src/utils/agent-tool-display.tsindex 7878965dc..ccaaa1e62 100644--- a/frontend/src/utils/agent-tool-display.ts+++ b/frontend/src/utils/agent-tool-display.ts@@ -119,7 +119,19 @@ export function getKnowledgeSearchSummaryHtml(const results = toolData.resultsconst count = (Array.isArray(results) ? results.length : 0) || Number(toolData.count) || 0- if (count === 0) return t('agentStream.search.noResults')+ if (count === 0) {+ // Retrieval found candidates but none cleared the relevance threshold, so the+ // turn answered from the fallback with nothing retrieved in its context. Say+ // that rather than "no matching content": the difference is what tells you to+ // look at the threshold instead of the knowledge base.+ const candidateCount = Number(toolData.candidate_count) || 0+ if (candidateCount > 0) {+ return t('agentStream.search.candidatesBelowThreshold', {+ count: `<strong>${candidateCount}</strong>`,+ })+ }+ return t('agentStream.search.noResults')+ }const searchSource = getRetrievalSearchSource(null, toolData)const webCount = Number(toolData.web_count) || 0diff --git a/internal/application/service/chat_pipeline/progress.go b/internal/application/service/chat_pipeline/progress.goindex 9750e4a79..e5425c828 100644--- a/internal/application/service/chat_pipeline/progress.go+++ b/internal/application/service/chat_pipeline/progress.go@@ -183,6 +183,21 @@ func EndRetrievalProgress(}count, docCount, webCount := retrievalResultBreakdown(chatManage)++ // ErrSearchNothing means retrieval short-circuited the pipeline into the+ // fallback answer: nothing survived filtering, and the fallback prompt gets+ // a knowledge-base listing rather than any retrieved chunk. So no chunk+ // reached the model, and none can be cited either. Reporting the raw hits as+ // the result count is what made the timeline promise results the answer never+ // saw — and offer a row with no references to open. The raw hits stay+ // available as candidates, which is the useful part when a threshold is what+ // rejected them.+ candidateCount := 0+ if stageErr == ErrSearchNothing {+ candidateCount = count+ count, docCount, webCount = 0, 0, 0+ }+searchSource := retrievalSearchSource(chatManage)if count > 0 {switch {@@ -197,10 +212,13 @@ func EndRetrievalProgress(success := stageErr == nil || stageErr == ErrSearchNothingoutput := ""if success {- if count == 0 {- output = "未检索到相关内容"- } else {+ switch {+ case count > 0:output = fmt.Sprintf("检索到 %d 条相关内容", count)+ case candidateCount > 0:+ output = fmt.Sprintf("命中 %d 条候选,相关性不足,未用于回答", candidateCount)+ default:+ output = "未检索到相关内容"}}@@ -220,10 +238,11 @@ func EndRetrievalProgress(Success: success,Duration: time.Since(start).Milliseconds(),Data: map[string]interface{}{- "count": count,- "doc_count": docCount,- "web_count": webCount,- "search_source": searchSource,+ "count": count,+ "doc_count": docCount,+ "web_count": webCount,+ "search_source": searchSource,+ "candidate_count": candidateCount,},},})diff --git a/internal/application/service/chat_pipeline/progress_test.go b/internal/application/service/chat_pipeline/progress_test.goindex d97703601..23008e745 100644--- a/internal/application/service/chat_pipeline/progress_test.go+++ b/internal/application/service/chat_pipeline/progress_test.go@@ -121,6 +121,52 @@ func TestRetrievalProgressEmitsSingleToolCallAndResult(t *testing.T) {assert.Equal(t, retrievalSourceKnowledge, resultData.Data["search_source"])}+// A turn whose candidates all fell below the relevance threshold answers from+// the fallback, which never sees a retrieved chunk. Reporting the raw hits as+// the result count claimed context the answer did not have — and offered a row+// with no references behind it.+func TestRetrievalProgressReportsNoResultsWhenPipelineFellBack(t *testing.T) {+ bus := &recordingEventBus{}+ cm := &types.ChatManage{+ PipelineRequest: types.PipelineRequest{SessionID: "sess-fallback"},+ PipelineContext: types.PipelineContext{EventBus: bus},+ PipelineState: types.PipelineState{+ SearchResult: []*types.SearchResult{{ID: "r1"}, {ID: "r2"}, {ID: "r3"}},+ },+ }++ progress := BeginRetrievalProgress(context.Background(), cm)+ require.NotNil(t, progress)+ EndRetrievalProgress(context.Background(), cm, progress, time.Now(), ErrSearchNothing)++ resultData, ok := bus.events[1].Data.(event.AgentToolResultData)+ require.True(t, ok)+ assert.True(t, resultData.Success)+ assert.Equal(t, 0, resultData.Data["count"])+ assert.Equal(t, 0, resultData.Data["doc_count"])+ assert.Equal(t, 0, resultData.Data["web_count"])+ assert.Equal(t, 3, resultData.Data["candidate_count"])+ assert.Equal(t, "命中 3 条候选,相关性不足,未用于回答", resultData.Output)+}++func TestRetrievalProgressReportsNothingFoundWhenThereWereNoCandidates(t *testing.T) {+ bus := &recordingEventBus{}+ cm := &types.ChatManage{+ PipelineRequest: types.PipelineRequest{SessionID: "sess-empty"},+ PipelineContext: types.PipelineContext{EventBus: bus},+ }++ progress := BeginRetrievalProgress(context.Background(), cm)+ require.NotNil(t, progress)+ EndRetrievalProgress(context.Background(), cm, progress, time.Now(), ErrSearchNothing)++ resultData, ok := bus.events[1].Data.(event.AgentToolResultData)+ require.True(t, ok)+ assert.Equal(t, 0, resultData.Data["count"])+ assert.Equal(t, 0, resultData.Data["candidate_count"])+ assert.Equal(t, "未检索到相关内容", resultData.Output)+}+func TestRetrievalProgressWebOnlySearchSource(t *testing.T) {bus := &recordingEventBus{}cm := &types.ChatManage{