fix(chat): 兜底回答不再把原始命中数报成检索结果数

检索阶段以 ErrSearchNothing 短路时会走兜底回答,而兜底 prompt 只拿到知识库的
文档标题清单,一条检索片段都没进模型上下文,引用集合同样为空。但进度条的计数
在 MergeResult / RerankResult 都为空时回退到原始 SearchResult,于是时间轴上写着
「找到 10 个结果」——既不是模型看到的上下文数,也没有引用可以点开。

现在兜底路径下 count / doc_count / web_count 归零,原始命中数放进新的
candidate_count,前端相应显示「命中 N 条候选,相关性不足,未用于回答」,与完全
没有候选的「未检索到相关内容」区分开:这个区别指向的是相关性阈值,而不是知识库。
main
wizardchen 2026-08-13 20:58:00 +08:00 committed by lyingbug
parent 9ed6266264
commit 49010d2526
9 changed files with 108 additions and 8 deletions

View File

@ -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)",

View File

@ -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)',

View File

@ -1262,6 +1262,7 @@ export default {
},
search: {
noResults: '일치하는 내용을 찾을 수 없습니다',
candidatesBelowThreshold: '후보 {count}개를 찾았지만 관련성이 부족해 답변에 사용하지 않았습니다',
foundResultsFromFiles: '{files}개 파일에서 {count}개 결과 발견',
foundResults: '{count}개 결과 발견',
foundMixedResults: '{count}개 결과 발견 ({docCount}개 문서, {webCount}개 웹)',

View File

@ -1262,6 +1262,7 @@ export default {
},
search: {
noResults: 'Совпадения не найдены',
candidatesBelowThreshold: 'Найдено кандидатов: {count}, ни один не подошёл по релевантности',
foundResultsFromFiles: 'Найдено {count} результат(ов) из {files} файл(ов)',
foundResults: 'Найдено {count} результат(ов)',
foundMixedResults: 'Найдено {count} результат(ов) ({docCount} док., {webCount} веб)',

View File

@ -1264,6 +1264,7 @@ export default {
},
search: {
noResults: '未找到匹配的内容',
candidatesBelowThreshold: '命中 {count} 条候选,相关性不足,未用于回答',
foundResultsFromFiles: '找到 {count} 个结果,来自 {files} 个文件',
foundResults: '找到 {count} 个结果',
foundMixedResults: '找到 {count} 个结果({docCount} 篇文档,{webCount} 条网页)',

View File

@ -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',

View File

@ -119,7 +119,19 @@ export function getKnowledgeSearchSummaryHtml(
const results = toolData.results
const 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) || 0

View File

@ -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 == ErrSearchNothing
output := ""
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,
},
},
})

View File

@ -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{