feat(agent): enhance suggested questions API with tag scopes
Update the SuggestedQuestionsRequest to include TagScopes for better filtering of knowledge items based on their parent knowledge bases. Modify related API documentation and frontend interfaces to accommodate the new structure. Ensure backend services handle the new tag scope logic correctly, including tests for the updated functionality.
This commit is contained in:
@@ -233,9 +233,11 @@ func hasKBRetrievalTargets(chatManage *types.ChatManage) bool {
|
||||
if chatManage == nil {
|
||||
return false
|
||||
}
|
||||
return len(chatManage.SearchTargets) > 0 ||
|
||||
len(chatManage.KnowledgeBaseIDs) > 0 ||
|
||||
len(chatManage.KnowledgeIDs) > 0
|
||||
return types.HasKnowledgeRetrievalScope(
|
||||
chatManage.SearchTargets,
|
||||
chatManage.KnowledgeBaseIDs,
|
||||
chatManage.KnowledgeIDs,
|
||||
)
|
||||
}
|
||||
|
||||
func retrievalSearchSource(chatManage *types.ChatManage) string {
|
||||
|
||||
@@ -52,12 +52,17 @@ func (p *PluginSearch) runQueryExpansion(ctx context.Context, chatManage *types.
|
||||
defer wgExp.Done()
|
||||
sem <- struct{}{}
|
||||
defer func() { <-sem }()
|
||||
vectorThreshold, keywordThreshold := t.RecallThresholds(
|
||||
chatManage.VectorThreshold,
|
||||
expKwTh,
|
||||
)
|
||||
paramsExp := types.SearchParams{
|
||||
QueryText: q,
|
||||
VectorThreshold: chatManage.VectorThreshold,
|
||||
KeywordThreshold: expKwTh,
|
||||
VectorThreshold: vectorThreshold,
|
||||
KeywordThreshold: keywordThreshold,
|
||||
MatchCount: expTopK,
|
||||
TagIDs: t.TagIDs,
|
||||
ScopeTagIDs: t.ScopeTagIDs,
|
||||
DisableVectorMatch: false,
|
||||
DisableKeywordsMatch: false,
|
||||
SkipContextEnrichment: true, // Pipeline handles context assembly in merge stage
|
||||
|
||||
@@ -71,19 +71,11 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
return ErrGetRerankModel.WithError(err)
|
||||
}
|
||||
|
||||
// Prepare passages for reranking (excluding DirectLoad results)
|
||||
// Prepare passages for reranking.
|
||||
var passages []string
|
||||
var candidatesToRerank []*types.SearchResult
|
||||
var directLoadResults []*types.SearchResult
|
||||
|
||||
for _, result := range chatManage.SearchResult {
|
||||
if result.MatchType == types.MatchTypeDirectLoad {
|
||||
directLoadResults = append(directLoadResults, result)
|
||||
pipelineInfo(ctx, "Rerank", "direct_load_skip", map[string]interface{}{
|
||||
"chunk_id": result.ID,
|
||||
})
|
||||
continue
|
||||
}
|
||||
passage := getEnrichedPassage(ctx, result)
|
||||
if strings.TrimSpace(passage) == "" {
|
||||
pipelineInfo(ctx, "Rerank", "empty_passage_skip", map[string]interface{}{
|
||||
@@ -99,15 +91,14 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
rerankCtx, rerankSpan := langfuse.GetManager().StartSpan(ctx, langfuse.SpanOptions{
|
||||
Name: "rerank",
|
||||
Input: map[string]interface{}{
|
||||
"query": chatManage.RewriteQuery,
|
||||
"candidate_count": len(candidatesToRerank),
|
||||
"direct_load_count": len(directLoadResults),
|
||||
"rerank_model_id": chatManage.RerankModelID,
|
||||
"threshold": chatManage.RerankThreshold,
|
||||
"rerank_top_k": chatManage.RerankTopK,
|
||||
"faq_priority": chatManage.FAQPriorityEnabled,
|
||||
"faq_score_boost": chatManage.FAQScoreBoost,
|
||||
"passages_preview": passagesPreview,
|
||||
"query": chatManage.RewriteQuery,
|
||||
"candidate_count": len(candidatesToRerank),
|
||||
"rerank_model_id": chatManage.RerankModelID,
|
||||
"threshold": chatManage.RerankThreshold,
|
||||
"rerank_top_k": chatManage.RerankTopK,
|
||||
"faq_priority": chatManage.FAQPriorityEnabled,
|
||||
"faq_score_boost": chatManage.FAQScoreBoost,
|
||||
"passages_preview": passagesPreview,
|
||||
},
|
||||
Metadata: map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
@@ -123,7 +114,6 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
pipelineInfo(ctx, "Rerank", "build_passages", map[string]interface{}{
|
||||
"total_cnt": len(chatManage.SearchResult),
|
||||
"candidate_cnt": len(candidatesToRerank),
|
||||
"direct_cnt": len(directLoadResults),
|
||||
})
|
||||
|
||||
var rerankResp []rerank.RankResult
|
||||
@@ -144,7 +134,7 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
"error": rerankErr.Error(),
|
||||
"candidate_cnt": len(candidatesToRerank),
|
||||
})
|
||||
chatManage.SearchResult = append(directLoadResults, candidatesToRerank...)
|
||||
chatManage.SearchResult = candidatesToRerank
|
||||
spanOutput = map[string]interface{}{
|
||||
"stage": "api_error_fallback",
|
||||
"candidate_count": len(candidatesToRerank),
|
||||
@@ -176,7 +166,7 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
"error": rerankErr.Error(),
|
||||
"candidate_cnt": len(candidatesToRerank),
|
||||
})
|
||||
chatManage.SearchResult = append(directLoadResults, candidatesToRerank...)
|
||||
chatManage.SearchResult = candidatesToRerank
|
||||
spanOutput = map[string]interface{}{
|
||||
"stage": "api_error_fallback",
|
||||
"candidate_count": len(candidatesToRerank),
|
||||
@@ -198,7 +188,7 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
for i := range chatManage.SearchResult {
|
||||
chatManage.SearchResult[i].Metadata = ensureMetadata(chatManage.SearchResult[i].Metadata)
|
||||
}
|
||||
reranked := make([]*types.SearchResult, 0, len(rerankResp)+len(directLoadResults))
|
||||
reranked := make([]*types.SearchResult, 0, len(rerankResp))
|
||||
|
||||
// Process reranked results
|
||||
for _, rr := range rerankResp {
|
||||
@@ -230,16 +220,6 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
reranked = append(reranked, sr)
|
||||
}
|
||||
|
||||
// Process direct load results (bypass rerank model, assume high relevance)
|
||||
for _, sr := range directLoadResults {
|
||||
base := sr.Score
|
||||
sr.Metadata["base_score"] = fmt.Sprintf("%.4f", base)
|
||||
modelScore := 1.0
|
||||
sr.Metadata["model_score"] = fmt.Sprintf("%.4f", modelScore)
|
||||
// Assign high model score for direct load items
|
||||
sr.Score = compositeScore(sr, modelScore, base)
|
||||
reranked = append(reranked, sr)
|
||||
}
|
||||
final := applyMMR(ctx, reranked, chatManage, min(len(reranked), max(1, chatManage.RerankTopK)), 0.7)
|
||||
chatManage.RerankResult = final
|
||||
|
||||
@@ -261,7 +241,6 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
spanOutput = buildRerankSpanOutput(
|
||||
candidatesToRerank,
|
||||
passages,
|
||||
directLoadResults,
|
||||
rawRerankResp,
|
||||
reranked,
|
||||
nil,
|
||||
@@ -274,7 +253,6 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
spanOutput = buildRerankSpanOutput(
|
||||
candidatesToRerank,
|
||||
passages,
|
||||
directLoadResults,
|
||||
rawRerankResp,
|
||||
reranked,
|
||||
chatManage.RerankResult,
|
||||
@@ -290,7 +268,6 @@ func (p *PluginRerank) OnEvent(ctx context.Context,
|
||||
func buildRerankSpanOutput(
|
||||
candidates []*types.SearchResult,
|
||||
passages []string,
|
||||
directLoad []*types.SearchResult,
|
||||
modelScores []rerank.RankResult,
|
||||
composite []*types.SearchResult,
|
||||
final []*types.SearchResult,
|
||||
@@ -319,7 +296,6 @@ func buildRerankSpanOutput(
|
||||
|
||||
out := map[string]interface{}{
|
||||
"candidate_count": len(candidates),
|
||||
"direct_load_count": len(directLoad),
|
||||
"model_result_count": len(modelScores),
|
||||
"composite_count": len(composite),
|
||||
"final_count": len(final),
|
||||
@@ -415,7 +391,7 @@ func (p *PluginRerank) rerank(ctx context.Context,
|
||||
// still has a reasonable score, keep it as a safety net. Skip fallback entirely
|
||||
// when the best score is too low — forcing irrelevant results is worse than
|
||||
// returning nothing and letting the caller handle the empty-result case.
|
||||
const fallbackMinScore = 0.15
|
||||
fallbackMinScore := rerankFallbackMinScore(chatManage.SearchTargets)
|
||||
if len(rankFilter) == 0 && len(rerankResp) > 0 && rerankResp[0].RelevanceScore >= fallbackMinScore {
|
||||
rankFilter = rerankResp[:1]
|
||||
pipelineInfo(ctx, "Rerank", "fallback_top1", map[string]interface{}{
|
||||
@@ -434,6 +410,16 @@ func (p *PluginRerank) rerank(ctx context.Context,
|
||||
return rankFilter, nil
|
||||
}
|
||||
|
||||
func rerankFallbackMinScore(searchTargets types.SearchTargets) float64 {
|
||||
if searchTargets.HasRecallThresholdOverride() {
|
||||
// The user explicitly constrained this turn to a tag/document scope.
|
||||
// Preserve its best candidate instead of letting a global rerank
|
||||
// threshold erase the entire authoritative scope.
|
||||
return 0
|
||||
}
|
||||
return 0.15
|
||||
}
|
||||
|
||||
// ensureMetadata ensures the metadata is not nil
|
||||
func ensureMetadata(m map[string]string) map[string]string {
|
||||
if m == nil {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package chatpipeline
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func TestRerankFallbackMinScoreForExplicitScope(t *testing.T) {
|
||||
if got := rerankFallbackMinScore(nil); got != 0.15 {
|
||||
t.Fatalf("default fallback minimum = %v, want 0.15", got)
|
||||
}
|
||||
|
||||
targets := types.SearchTargets{{DisableRecallThresholds: true}}
|
||||
if got := rerankFallbackMinScore(targets); got != 0 {
|
||||
t.Fatalf("explicit-scope fallback minimum = %v, want 0", got)
|
||||
}
|
||||
}
|
||||
@@ -63,7 +63,11 @@ func (p *PluginSearch) OnEvent(ctx context.Context,
|
||||
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
|
||||
) *PluginError {
|
||||
// Check if we have search targets or web search enabled
|
||||
hasKBTargets := len(chatManage.SearchTargets) > 0 || len(chatManage.KnowledgeBaseIDs) > 0 || len(chatManage.KnowledgeIDs) > 0
|
||||
hasKBTargets := types.HasKnowledgeRetrievalScope(
|
||||
chatManage.SearchTargets,
|
||||
chatManage.KnowledgeBaseIDs,
|
||||
chatManage.KnowledgeIDs,
|
||||
)
|
||||
if !hasKBTargets && !chatManage.WebSearchEnabled {
|
||||
pipelineError(ctx, "Search", "kb_not_found", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
@@ -456,8 +460,7 @@ func (p *PluginSearch) searchByTargets(
|
||||
return results
|
||||
}
|
||||
|
||||
// searchSingleTarget handles the search logic for a single SearchTarget
|
||||
// with specific knowledge IDs, including direct chunk loading and HybridSearch.
|
||||
// searchSingleTarget performs hybrid retrieval inside one constrained target.
|
||||
func (p *PluginSearch) searchSingleTarget(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
@@ -467,46 +470,33 @@ func (p *PluginSearch) searchSingleTarget(
|
||||
mu *sync.Mutex,
|
||||
results *[]*types.SearchResult,
|
||||
) {
|
||||
searchKnowledgeIDs := t.KnowledgeIDs
|
||||
|
||||
if t.Type == types.SearchTargetTypeKnowledge && !t.DisableDirectLoad {
|
||||
directResults, skippedIDs := p.tryDirectChunkLoading(ctx, chatManage.TenantID, t.KnowledgeIDs)
|
||||
|
||||
if len(directResults) > 0 {
|
||||
for _, r := range directResults {
|
||||
r.KnowledgeBaseID = t.KnowledgeBaseID
|
||||
}
|
||||
pipelineInfo(ctx, "Search", "direct_load", map[string]interface{}{
|
||||
"kb_id": t.KnowledgeBaseID,
|
||||
"loaded_count": len(directResults),
|
||||
"skipped_ids": len(skippedIDs),
|
||||
})
|
||||
mu.Lock()
|
||||
*results = append(*results, directResults...)
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
if len(skippedIDs) == 0 && len(t.KnowledgeIDs) > 0 {
|
||||
return
|
||||
}
|
||||
searchKnowledgeIDs = skippedIDs
|
||||
}
|
||||
|
||||
if t.Type == types.SearchTargetTypeKnowledge && len(searchKnowledgeIDs) == 0 {
|
||||
if t.Type == types.SearchTargetTypeKnowledge && len(t.KnowledgeIDs) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
vectorThreshold, keywordThreshold := t.RecallThresholds(
|
||||
chatManage.VectorThreshold,
|
||||
chatManage.KeywordThreshold,
|
||||
)
|
||||
if t.DisableRecallThresholds {
|
||||
pipelineInfo(ctx, "Search", "explicit_scope_threshold_override", map[string]interface{}{
|
||||
"kb_id": t.KnowledgeBaseID,
|
||||
"knowledge_id_count": len(t.KnowledgeIDs),
|
||||
"tag_id_count": len(t.TagIDs),
|
||||
})
|
||||
}
|
||||
params := types.SearchParams{
|
||||
QueryText: queryText,
|
||||
QueryEmbedding: queryEmbedding,
|
||||
VectorThreshold: chatManage.VectorThreshold,
|
||||
KeywordThreshold: chatManage.KeywordThreshold,
|
||||
VectorThreshold: vectorThreshold,
|
||||
KeywordThreshold: keywordThreshold,
|
||||
MatchCount: chatManage.EmbeddingTopK,
|
||||
TagIDs: t.TagIDs,
|
||||
ScopeTagIDs: t.ScopeTagIDs,
|
||||
SkipContextEnrichment: true,
|
||||
}
|
||||
if t.Type == types.SearchTargetTypeKnowledge {
|
||||
params.KnowledgeIDs = searchKnowledgeIDs
|
||||
params.KnowledgeIDs = t.KnowledgeIDs
|
||||
}
|
||||
res, err := p.knowledgeBaseService.HybridSearch(ctx, t.KnowledgeBaseID, params)
|
||||
if err != nil {
|
||||
@@ -528,96 +518,6 @@ func (p *PluginSearch) searchSingleTarget(
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
// tryDirectChunkLoading attempts to load chunks for given knowledge IDs directly
|
||||
// Returns loaded results and a list of knowledge IDs that were skipped (e.g. due to size limits)
|
||||
func (p *PluginSearch) tryDirectChunkLoading(ctx context.Context, tenantID uint64, knowledgeIDs []string) ([]*types.SearchResult, []string) {
|
||||
if len(knowledgeIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Limit direct loading to avoid OOM or context overflow
|
||||
// 50 chunks * ~500 chars/chunk ~= 25k chars
|
||||
const maxTotalChunks = 50
|
||||
|
||||
var allChunks []*types.Chunk
|
||||
var skippedIDs []string
|
||||
loadedKnowledgeIDs := make(map[string]bool)
|
||||
|
||||
for _, kid := range knowledgeIDs {
|
||||
// Optimization: Check chunk count first if possible?
|
||||
chunks, err := p.chunkService.ListChunksByKnowledgeID(ctx, kid)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "DirectLoad: Failed to list chunks for knowledge %s: %v", kid, err)
|
||||
skippedIDs = append(skippedIDs, kid)
|
||||
continue
|
||||
}
|
||||
|
||||
if len(allChunks)+len(chunks) > maxTotalChunks {
|
||||
logger.Infof(ctx, "DirectLoad: Skipped knowledge %s due to size limit (%d + %d > %d)",
|
||||
kid, len(allChunks), len(chunks), maxTotalChunks)
|
||||
skippedIDs = append(skippedIDs, kid)
|
||||
continue
|
||||
}
|
||||
allChunks = append(allChunks, chunks...)
|
||||
loadedKnowledgeIDs[kid] = true
|
||||
}
|
||||
|
||||
if len(allChunks) == 0 {
|
||||
return nil, skippedIDs
|
||||
}
|
||||
|
||||
// Fetch Knowledge metadata
|
||||
var uniqueKIDs []string
|
||||
for kid := range loadedKnowledgeIDs {
|
||||
uniqueKIDs = append(uniqueKIDs, kid)
|
||||
}
|
||||
|
||||
knowledgeMap := make(map[string]*types.Knowledge)
|
||||
if len(uniqueKIDs) > 0 {
|
||||
knowledges, err := p.knowledgeService.GetKnowledgeBatchWithSharedAccess(ctx, tenantID, uniqueKIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "DirectLoad: Failed to fetch knowledge batch: %v", err)
|
||||
// Continue without metadata
|
||||
} else {
|
||||
for _, k := range knowledges {
|
||||
knowledgeMap[k.ID] = k
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var results []*types.SearchResult
|
||||
for _, chunk := range allChunks {
|
||||
res := &types.SearchResult{
|
||||
ID: chunk.ID,
|
||||
Content: chunk.Content,
|
||||
Score: 1.0, // Maximum score for direct matches
|
||||
KnowledgeID: chunk.KnowledgeID,
|
||||
ChunkIndex: chunk.ChunkIndex,
|
||||
MatchType: types.MatchTypeDirectLoad,
|
||||
ChunkType: string(chunk.ChunkType),
|
||||
ParentChunkID: chunk.ParentChunkID,
|
||||
ImageInfo: chunk.ImageInfo,
|
||||
ChunkMetadata: chunk.Metadata,
|
||||
StartAt: chunk.StartAt,
|
||||
EndAt: chunk.EndAt,
|
||||
}
|
||||
|
||||
if k, ok := knowledgeMap[chunk.KnowledgeID]; ok {
|
||||
res.KnowledgeTitle = k.Title
|
||||
res.KnowledgeFilename = k.FileName
|
||||
res.KnowledgeSource = k.Source
|
||||
res.KnowledgeChannel = k.Channel
|
||||
res.Metadata = k.GetMetadata()
|
||||
}
|
||||
|
||||
results = append(results, res)
|
||||
}
|
||||
|
||||
searchutil.EnrichSearchResultsImageInfo(ctx, p.chunkService.GetRepository(), tenantID, results)
|
||||
|
||||
return results, skippedIDs
|
||||
}
|
||||
|
||||
// searchWebIfEnabled executes web search when enabled and returns converted results
|
||||
func (p *PluginSearch) searchWebIfEnabled(ctx context.Context, chatManage *types.ChatManage) []*types.SearchResult {
|
||||
if !chatManage.WebSearchEnabled || p.webSearchService == nil || p.tenantService == nil {
|
||||
|
||||
Reference in New Issue
Block a user