feat: enhance input field and agent stream display with improved handling and sanitization
- Added blur handling for the textarea in the Input-field component to prevent errors when navigating away from the component. - Improved the sanitization process in the AgentStreamDisplay component to preserve specific tags during markdown processing, ensuring accurate content display. - Introduced new methods for handling FAQ-specific post-processing in the knowledge base service, optimizing retrieval and filtering of search results. These changes enhance user experience by improving input handling and content rendering in the chat interface.
This commit is contained in:
@@ -1375,6 +1375,11 @@ const createSession = async (val: string) => {
|
||||
kb_type: item.type === 'kb' ? (item.kbType || 'document') : undefined
|
||||
}));
|
||||
const imageFiles = uploadedImages.value.map(img => img.file);
|
||||
// Blur the textarea BEFORE emitting, so that when the parent navigates away
|
||||
// and Vue unmounts this component, TDesign's blur handler won't fire on a
|
||||
// detached DOM element (which causes getComputedStyle to throw).
|
||||
const textarea = getTextareaEl();
|
||||
if (textarea) textarea.blur();
|
||||
emit('send-msg', val, selectedModelId.value, mentionedItems, imageFiles);
|
||||
// Clean up image previews
|
||||
uploadedImages.value.forEach(img => URL.revokeObjectURL(img.preview));
|
||||
@@ -1560,6 +1565,9 @@ const handleSelectAgent = (agent: CustomAgent, sourceTenantId?: string) => {
|
||||
}
|
||||
|
||||
const clearvalue = () => {
|
||||
// Guard: only clear when the textarea DOM element is still mounted,
|
||||
// otherwise TDesign's autosize will call getComputedStyle on a non-Element.
|
||||
if (!getTextareaEl()) return;
|
||||
query.value = "";
|
||||
}
|
||||
|
||||
|
||||
@@ -1352,7 +1352,21 @@ const getTokens = (content: any) => {
|
||||
const contentStr = typeof content === 'string' ? content : String(content || '');
|
||||
if (!contentStr.trim()) return [];
|
||||
|
||||
const processed = preprocessMarkdown(sanitizeForDisplay(contentStr));
|
||||
// Extract <kb.../> and <web.../> tags before sanitization to prevent
|
||||
// sanitizeForDisplay from stripping chunk_id labels and UUIDs inside them.
|
||||
const tagPlaceholders: string[] = [];
|
||||
const preserved = contentStr.replace(/<(?:kb|web)\b[^>]*\/>/g, (match) => {
|
||||
const idx = tagPlaceholders.length;
|
||||
tagPlaceholders.push(match);
|
||||
return `\x00TAG${idx}\x00`;
|
||||
});
|
||||
|
||||
let sanitized = sanitizeForDisplay(preserved);
|
||||
|
||||
// Restore preserved tags
|
||||
sanitized = sanitized.replace(/\x00TAG(\d+)\x00/g, (_, idx) => tagPlaceholders[Number(idx)]);
|
||||
|
||||
const processed = preprocessMarkdown(sanitized);
|
||||
return marked.lexer(processed);
|
||||
};
|
||||
|
||||
|
||||
@@ -3,11 +3,8 @@ package chatpipline
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/searchutil"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
@@ -33,7 +30,16 @@ func (p *PluginMerge) ActivationEvents() []types.EventType {
|
||||
return []types.EventType{types.CHUNK_MERGE}
|
||||
}
|
||||
|
||||
// OnEvent processes the CHUNK_MERGE event to merge search result chunks
|
||||
// OnEvent processes the CHUNK_MERGE event to merge search result chunks.
|
||||
// The merge pipeline is:
|
||||
// 1. Select input (rerank or search fallback)
|
||||
// 2. Deduplicate by ID and content signature
|
||||
// 3. Inject relevant history references
|
||||
// 4. Resolve parent chunks (child → parent content)
|
||||
// 5. Group by knowledge source + chunk type, merge overlapping ranges
|
||||
// 6. Populate FAQ answers
|
||||
// 7. Expand short contexts with neighboring chunks
|
||||
// 8. Final deduplication (catches duplicates introduced by steps 4-7)
|
||||
func (p *PluginMerge) OnEvent(ctx context.Context,
|
||||
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
|
||||
) *PluginError {
|
||||
@@ -42,46 +48,19 @@ func (p *PluginMerge) OnEvent(ctx context.Context,
|
||||
"candidate_cnt": len(chatManage.RerankResult),
|
||||
})
|
||||
|
||||
// Use rerank results if available, fallback to search results
|
||||
searchResult := chatManage.RerankResult
|
||||
if len(searchResult) == 0 {
|
||||
pipelineWarn(ctx, "Merge", "fallback", map[string]interface{}{
|
||||
"reason": "empty_rerank_result",
|
||||
})
|
||||
searchResult = chatManage.SearchResult
|
||||
// Sort by score descending so dedup keeps highest-scored entries
|
||||
sort.Slice(searchResult, func(i, j int) bool {
|
||||
return searchResult[i].Score > searchResult[j].Score
|
||||
})
|
||||
}
|
||||
// Step 1: Select input
|
||||
searchResult := p.selectInputResults(ctx, chatManage)
|
||||
|
||||
// Deduplicate after rerank so higher-scored duplicates are preferred
|
||||
beforeDedup := len(searchResult)
|
||||
searchResult = removeDuplicateResults(searchResult)
|
||||
pipelineInfo(ctx, "Merge", "dedup_summary", map[string]interface{}{
|
||||
"before": beforeDedup,
|
||||
"after": len(searchResult),
|
||||
})
|
||||
// Step 2: Initial dedup
|
||||
searchResult = p.dedup(ctx, "dedup_summary", searchResult)
|
||||
|
||||
// Inject relevant results from chat history with similarity filtering.
|
||||
// History references were produced for a previous query, so we only keep
|
||||
// those that are textually relevant to the current query to avoid injecting
|
||||
// stale or off-topic context.
|
||||
historyResults := filterHistoryResults(ctx, chatManage, searchResult)
|
||||
if len(historyResults) > 0 {
|
||||
pipelineInfo(ctx, "Merge", "history_inject", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"history_hits": len(historyResults),
|
||||
})
|
||||
searchResult = append(searchResult, historyResults...)
|
||||
searchResult = removeDuplicateResults(searchResult)
|
||||
}
|
||||
// Step 3: Inject history references
|
||||
searchResult = p.injectHistoryResults(ctx, chatManage, searchResult)
|
||||
|
||||
pipelineInfo(ctx, "Merge", "candidate_ready", map[string]interface{}{
|
||||
"chunk_cnt": len(searchResult),
|
||||
})
|
||||
|
||||
// If there are no search results, return early
|
||||
if len(searchResult) == 0 {
|
||||
pipelineWarn(ctx, "Merge", "output", map[string]interface{}{
|
||||
"chunk_cnt": 0,
|
||||
@@ -90,24 +69,92 @@ func (p *PluginMerge) OnEvent(ctx context.Context,
|
||||
return next()
|
||||
}
|
||||
|
||||
// Resolve parent chunks: replace child content with fuller parent content
|
||||
// Step 4: Resolve parent chunks
|
||||
searchResult = p.resolveParentChunks(ctx, chatManage, searchResult)
|
||||
|
||||
// Group chunks by their knowledge source ID
|
||||
// Step 5: Group by knowledge/chunkType and merge overlapping ranges
|
||||
mergedChunks := p.groupAndMergeOverlapping(ctx, searchResult)
|
||||
|
||||
// Step 6: Populate FAQ answers
|
||||
mergedChunks = p.populateFAQAnswers(ctx, chatManage, mergedChunks)
|
||||
|
||||
// Step 7: Expand short contexts
|
||||
mergedChunks = p.expandShortContextWithNeighbors(ctx, chatManage, mergedChunks)
|
||||
|
||||
// Step 8: Final dedup (catches duplicates from parent resolution / expansion)
|
||||
mergedChunks = p.dedup(ctx, "final_dedup", mergedChunks)
|
||||
|
||||
chatManage.MergeResult = mergedChunks
|
||||
return next()
|
||||
}
|
||||
|
||||
// selectInputResults picks rerank results if available, falling back to search
|
||||
// results sorted by score descending.
|
||||
func (p *PluginMerge) selectInputResults(ctx context.Context, chatManage *types.ChatManage) []*types.SearchResult {
|
||||
if len(chatManage.RerankResult) > 0 {
|
||||
return chatManage.RerankResult
|
||||
}
|
||||
pipelineWarn(ctx, "Merge", "fallback", map[string]interface{}{
|
||||
"reason": "empty_rerank_result",
|
||||
})
|
||||
result := chatManage.SearchResult
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
return result[i].Score > result[j].Score
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
// dedup wraps removeDuplicateResults with before/after logging.
|
||||
func (p *PluginMerge) dedup(ctx context.Context, label string, results []*types.SearchResult) []*types.SearchResult {
|
||||
before := len(results)
|
||||
out := removeDuplicateResults(results)
|
||||
if len(out) < before {
|
||||
pipelineInfo(ctx, "Merge", label, map[string]interface{}{
|
||||
"before": before,
|
||||
"after": len(out),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// injectHistoryResults appends relevant history references to the current results
|
||||
// and deduplicates the combined set.
|
||||
func (p *PluginMerge) injectHistoryResults(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
current []*types.SearchResult,
|
||||
) []*types.SearchResult {
|
||||
historyResults := filterHistoryResults(ctx, chatManage, current)
|
||||
if len(historyResults) == 0 {
|
||||
return current
|
||||
}
|
||||
pipelineInfo(ctx, "Merge", "history_inject", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"history_hits": len(historyResults),
|
||||
})
|
||||
combined := append(current, historyResults...)
|
||||
return removeDuplicateResults(combined)
|
||||
}
|
||||
|
||||
// groupAndMergeOverlapping groups chunks by KnowledgeID + ChunkType, then merges
|
||||
// overlapping ranges within each group using mergeOverlappingChunks.
|
||||
func (p *PluginMerge) groupAndMergeOverlapping(ctx context.Context, results []*types.SearchResult) []*types.SearchResult {
|
||||
// Group by KnowledgeID → ChunkType
|
||||
knowledgeGroup := make(map[string]map[string][]*types.SearchResult)
|
||||
for _, chunk := range searchResult {
|
||||
for _, chunk := range results {
|
||||
if _, ok := knowledgeGroup[chunk.KnowledgeID]; !ok {
|
||||
knowledgeGroup[chunk.KnowledgeID] = make(map[string][]*types.SearchResult)
|
||||
}
|
||||
knowledgeGroup[chunk.KnowledgeID][chunk.ChunkType] = append(knowledgeGroup[chunk.KnowledgeID][chunk.ChunkType], chunk)
|
||||
knowledgeGroup[chunk.KnowledgeID][chunk.ChunkType] = append(
|
||||
knowledgeGroup[chunk.KnowledgeID][chunk.ChunkType], chunk,
|
||||
)
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "Merge", "group_summary", map[string]interface{}{
|
||||
"knowledge_cnt": len(knowledgeGroup),
|
||||
})
|
||||
|
||||
mergedChunks := []*types.SearchResult{}
|
||||
// Process each knowledge source separately
|
||||
var mergedChunks []*types.SearchResult
|
||||
for knowledgeID, chunkGroup := range knowledgeGroup {
|
||||
for _, chunks := range chunkGroup {
|
||||
pipelineInfo(ctx, "Merge", "group_process", map[string]interface{}{
|
||||
@@ -115,7 +162,7 @@ func (p *PluginMerge) OnEvent(ctx context.Context,
|
||||
"chunk_cnt": len(chunks),
|
||||
})
|
||||
|
||||
// Sort chunks by their start position in the original document
|
||||
// Sort by start position, then by end position
|
||||
sort.Slice(chunks, func(i, j int) bool {
|
||||
if chunks[i].StartAt == chunks[j].StartAt {
|
||||
return chunks[i].EndAt < chunks[j].EndAt
|
||||
@@ -123,69 +170,21 @@ func (p *PluginMerge) OnEvent(ctx context.Context,
|
||||
return chunks[i].StartAt < chunks[j].StartAt
|
||||
})
|
||||
|
||||
// Merge overlapping or adjacent chunks
|
||||
knowledgeMergedChunks := []*types.SearchResult{chunks[0]}
|
||||
for i := 1; i < len(chunks); i++ {
|
||||
lastChunk := knowledgeMergedChunks[len(knowledgeMergedChunks)-1]
|
||||
// If the current chunk starts after the last chunk ends, add it to the merged chunks
|
||||
if chunks[i].StartAt > lastChunk.EndAt {
|
||||
knowledgeMergedChunks = append(knowledgeMergedChunks, chunks[i])
|
||||
continue
|
||||
}
|
||||
// Merge overlapping chunks
|
||||
if chunks[i].EndAt > lastChunk.EndAt {
|
||||
contentRunes := []rune(chunks[i].Content)
|
||||
offset := len(contentRunes) - (chunks[i].EndAt - lastChunk.EndAt)
|
||||
lastChunk.Content = lastChunk.Content + string(contentRunes[offset:])
|
||||
lastChunk.EndAt = chunks[i].EndAt
|
||||
lastChunk.SubChunkID = append(lastChunk.SubChunkID, chunks[i].ID)
|
||||
|
||||
if err := mergeImageInfo(ctx, lastChunk, chunks[i]); err != nil {
|
||||
pipelineWarn(ctx, "Merge", "image_merge", map[string]interface{}{
|
||||
"knowledge_id": knowledgeID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Fully contained: track the subsumed chunk and merge its ImageInfo
|
||||
if !containsID(lastChunk.SubChunkID, chunks[i].ID) {
|
||||
lastChunk.SubChunkID = append(lastChunk.SubChunkID, chunks[i].ID)
|
||||
}
|
||||
if err := mergeImageInfo(ctx, lastChunk, chunks[i]); err != nil {
|
||||
pipelineWarn(ctx, "Merge", "image_merge_contained", map[string]interface{}{
|
||||
"knowledge_id": knowledgeID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
}
|
||||
if chunks[i].Score > lastChunk.Score {
|
||||
lastChunk.Score = chunks[i].Score
|
||||
}
|
||||
}
|
||||
grouped := p.mergeOverlappingChunks(ctx, knowledgeID, chunks)
|
||||
|
||||
pipelineInfo(ctx, "Merge", "group_output", map[string]interface{}{
|
||||
"knowledge_id": knowledgeID,
|
||||
"merged_chunks": len(knowledgeMergedChunks),
|
||||
"merged_chunks": len(grouped),
|
||||
})
|
||||
|
||||
// Sort merged chunks by their score (highest first)
|
||||
sort.Slice(knowledgeMergedChunks, func(i, j int) bool {
|
||||
return knowledgeMergedChunks[i].Score > knowledgeMergedChunks[j].Score
|
||||
})
|
||||
|
||||
mergedChunks = append(mergedChunks, knowledgeMergedChunks...)
|
||||
mergedChunks = append(mergedChunks, grouped...)
|
||||
}
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "Merge", "output", map[string]interface{}{
|
||||
"merged_total": len(mergedChunks),
|
||||
})
|
||||
|
||||
mergedChunks = p.populateFAQAnswers(ctx, chatManage, mergedChunks)
|
||||
mergedChunks = p.expandShortContextWithNeighbors(ctx, chatManage, mergedChunks)
|
||||
|
||||
chatManage.MergeResult = mergedChunks
|
||||
return next()
|
||||
return mergedChunks
|
||||
}
|
||||
|
||||
// resolveParentChunks replaces child chunk content with parent chunk content
|
||||
@@ -358,611 +357,3 @@ func (p *PluginMerge) collectParentImageInfo(
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// filterHistoryResults retrieves history references and filters them by
|
||||
// textual similarity to the current query. Only references that are above
|
||||
// a Jaccard similarity threshold are kept, and their scores are discounted
|
||||
// to reflect that they were not directly retrieved for the current query.
|
||||
// Results already present in currentResults (by chunk ID) are excluded.
|
||||
func filterHistoryResults(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
currentResults []*types.SearchResult,
|
||||
) []*types.SearchResult {
|
||||
const (
|
||||
// minSimilarity is the minimum Jaccard similarity between the current
|
||||
// query and a history chunk's content for it to be injected.
|
||||
minSimilarity = 0.15
|
||||
// historyScoreDiscount reduces the original score of history results
|
||||
// to rank them below freshly-retrieved results of similar relevance.
|
||||
historyScoreDiscount = 0.6
|
||||
// maxHistoryResults caps the number of history results injected to
|
||||
// avoid overwhelming the context with stale references.
|
||||
maxHistoryResults = 3
|
||||
)
|
||||
|
||||
raw := getSearchResultFromHistory(chatManage)
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Build a set of chunk IDs already in current results for fast dedup
|
||||
existingIDs := make(map[string]struct{}, len(currentResults))
|
||||
for _, r := range currentResults {
|
||||
existingIDs[r.ID] = struct{}{}
|
||||
}
|
||||
|
||||
// Use RewriteQuery if available (it's the cleaned-up retrieval query),
|
||||
// otherwise fall back to the original query.
|
||||
query := chatManage.RewriteQuery
|
||||
if query == "" {
|
||||
query = chatManage.Query
|
||||
}
|
||||
queryTokens := searchutil.TokenizeSimple(query)
|
||||
|
||||
var filtered []*types.SearchResult
|
||||
for _, r := range raw {
|
||||
if _, exists := existingIDs[r.ID]; exists {
|
||||
continue
|
||||
}
|
||||
contentTokens := searchutil.TokenizeSimple(r.Content)
|
||||
sim := searchutil.Jaccard(queryTokens, contentTokens)
|
||||
if sim < minSimilarity {
|
||||
pipelineInfo(ctx, "Merge", "history_filter_drop", map[string]interface{}{
|
||||
"chunk_id": r.ID,
|
||||
"similarity": sim,
|
||||
})
|
||||
continue
|
||||
}
|
||||
r.MatchType = types.MatchTypeHistory
|
||||
r.Score = r.Score * historyScoreDiscount
|
||||
r.Metadata = ensureMetadata(r.Metadata)
|
||||
r.Metadata["history_similarity"] = strings.TrimRight(strings.TrimRight(
|
||||
fmt.Sprintf("%.4f", sim), "0"), ".")
|
||||
filtered = append(filtered, r)
|
||||
|
||||
pipelineInfo(ctx, "Merge", "history_filter_keep", map[string]interface{}{
|
||||
"chunk_id": r.ID,
|
||||
"similarity": sim,
|
||||
"new_score": r.Score,
|
||||
})
|
||||
|
||||
if len(filtered) >= maxHistoryResults {
|
||||
break
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
// mergeImageInfo 合并两个chunk的ImageInfo
|
||||
func mergeImageInfo(ctx context.Context, target *types.SearchResult, source *types.SearchResult) error {
|
||||
// 如果source没有ImageInfo,不需要合并
|
||||
if source.ImageInfo == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var sourceImageInfos []types.ImageInfo
|
||||
if err := json.Unmarshal([]byte(source.ImageInfo), &sourceImageInfos); err != nil {
|
||||
pipelineWarn(ctx, "Merge", "image_unmarshal_source", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// 如果source的ImageInfo为空,不需要合并
|
||||
if len(sourceImageInfos) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 处理target的ImageInfo
|
||||
var targetImageInfos []types.ImageInfo
|
||||
if target.ImageInfo != "" {
|
||||
if err := json.Unmarshal([]byte(target.ImageInfo), &targetImageInfos); err != nil {
|
||||
pipelineWarn(ctx, "Merge", "image_unmarshal_target", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
// 如果目标解析失败,直接使用源数据
|
||||
target.ImageInfo = source.ImageInfo
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// 合并ImageInfo
|
||||
targetImageInfos = append(targetImageInfos, sourceImageInfos...)
|
||||
|
||||
// 去重
|
||||
uniqueMap := make(map[string]bool)
|
||||
uniqueImageInfos := make([]types.ImageInfo, 0, len(targetImageInfos))
|
||||
|
||||
for _, imgInfo := range targetImageInfos {
|
||||
// 使用URL作为唯一标识
|
||||
if imgInfo.URL != "" && !uniqueMap[imgInfo.URL] {
|
||||
uniqueMap[imgInfo.URL] = true
|
||||
uniqueImageInfos = append(uniqueImageInfos, imgInfo)
|
||||
}
|
||||
}
|
||||
|
||||
// 序列化合并后的ImageInfo
|
||||
mergedImageInfoJSON, err := json.Marshal(uniqueImageInfos)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "image_marshal", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// 更新目标chunk的ImageInfo
|
||||
target.ImageInfo = string(mergedImageInfoJSON)
|
||||
pipelineInfo(ctx, "Merge", "image_merged", map[string]interface{}{
|
||||
"image_refs": len(uniqueImageInfos),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// populateFAQAnswers populates FAQ answers for the search results
|
||||
func (p *PluginMerge) populateFAQAnswers(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
results []*types.SearchResult,
|
||||
) []*types.SearchResult {
|
||||
if len(results) == 0 || p.chunkRepo == nil {
|
||||
return results
|
||||
}
|
||||
|
||||
tenantID, _ := types.TenantIDFromContext(ctx)
|
||||
if tenantID == 0 && chatManage != nil {
|
||||
tenantID = chatManage.TenantID
|
||||
}
|
||||
if tenantID == 0 {
|
||||
pipelineWarn(ctx, "Merge", "faq_enrich_skip", map[string]interface{}{
|
||||
"reason": "missing_tenant",
|
||||
})
|
||||
return results
|
||||
}
|
||||
|
||||
chunkResultMap := make(map[string][]*types.SearchResult)
|
||||
chunkIDSet := make(map[string]struct{})
|
||||
for _, r := range results {
|
||||
if r == nil || r.ID == "" {
|
||||
continue
|
||||
}
|
||||
if r.ChunkType != string(types.ChunkTypeFAQ) {
|
||||
continue
|
||||
}
|
||||
chunkResultMap[r.ID] = append(chunkResultMap[r.ID], r)
|
||||
if _, exists := chunkIDSet[r.ID]; !exists {
|
||||
chunkIDSet[r.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
if len(chunkIDSet) == 0 {
|
||||
return results
|
||||
}
|
||||
|
||||
chunkIDs := make([]string, 0, len(chunkIDSet))
|
||||
for id := range chunkIDSet {
|
||||
chunkIDs = append(chunkIDs, id)
|
||||
}
|
||||
|
||||
chunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "faq_chunk_fetch_failed", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return results
|
||||
}
|
||||
|
||||
updated := 0
|
||||
for _, chunk := range chunks {
|
||||
if chunk == nil {
|
||||
continue
|
||||
}
|
||||
meta, err := chunk.FAQMetadata()
|
||||
if err != nil || meta == nil {
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "faq_metadata_parse_failed", map[string]interface{}{
|
||||
"chunk_id": chunk.ID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
content := buildFAQAnswerContent(meta)
|
||||
if content == "" {
|
||||
continue
|
||||
}
|
||||
for _, r := range chunkResultMap[chunk.ID] {
|
||||
if r == nil {
|
||||
continue
|
||||
}
|
||||
r.Content = content
|
||||
updated++
|
||||
}
|
||||
}
|
||||
|
||||
if updated > 0 {
|
||||
pipelineInfo(ctx, "Merge", "faq_content_enriched", map[string]interface{}{
|
||||
"chunk_cnt": updated,
|
||||
})
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
// buildFAQAnswerContent builds the content of a FAQ answer
|
||||
func buildFAQAnswerContent(meta *types.FAQChunkMetadata) string {
|
||||
if meta == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
question := strings.TrimSpace(meta.StandardQuestion)
|
||||
answers := make([]string, 0, len(meta.Answers))
|
||||
for _, ans := range meta.Answers {
|
||||
if trimmed := strings.TrimSpace(ans); trimmed != "" {
|
||||
answers = append(answers, trimmed)
|
||||
}
|
||||
}
|
||||
|
||||
if question == "" && len(answers) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
if question != "" {
|
||||
builder.WriteString("Q: ")
|
||||
builder.WriteString(question)
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
|
||||
if len(answers) > 0 {
|
||||
builder.WriteString("Answer:\n")
|
||||
for _, ans := range answers {
|
||||
builder.WriteString("- ")
|
||||
builder.WriteString(ans)
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
return strings.TrimSpace(builder.String())
|
||||
}
|
||||
|
||||
// expandShortContextWithNeighbors expands the short context with neighbors
|
||||
func (p *PluginMerge) expandShortContextWithNeighbors(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
results []*types.SearchResult,
|
||||
) []*types.SearchResult {
|
||||
const (
|
||||
minLen = 350
|
||||
maxLen = 850
|
||||
)
|
||||
|
||||
if len(results) == 0 || p.chunkRepo == nil {
|
||||
return results
|
||||
}
|
||||
|
||||
tenantID, _ := types.TenantIDFromContext(ctx)
|
||||
if tenantID == 0 && chatManage != nil {
|
||||
tenantID = chatManage.TenantID
|
||||
}
|
||||
if tenantID == 0 {
|
||||
pipelineWarn(ctx, "Merge", "expand_skip", map[string]interface{}{
|
||||
"reason": "missing_tenant",
|
||||
})
|
||||
return results
|
||||
}
|
||||
|
||||
type targetInfo struct {
|
||||
result *types.SearchResult
|
||||
}
|
||||
|
||||
targets := make([]targetInfo, 0)
|
||||
baseIDsSet := make(map[string]struct{})
|
||||
|
||||
for _, r := range results {
|
||||
if r == nil || r.ID == "" || r.Content == "" {
|
||||
continue
|
||||
}
|
||||
if r.ChunkType != string(types.ChunkTypeText) {
|
||||
continue
|
||||
}
|
||||
if runeLen(r.Content) >= minLen {
|
||||
continue
|
||||
}
|
||||
targets = append(targets, targetInfo{result: r})
|
||||
baseIDsSet[r.ID] = struct{}{}
|
||||
pipelineInfo(ctx, "Merge", "need_expand", map[string]interface{}{
|
||||
"chunk_id": r.ID,
|
||||
"content": r.Content,
|
||||
"chunk_type": r.ChunkType,
|
||||
"len": runeLen(r.Content),
|
||||
})
|
||||
}
|
||||
|
||||
if len(targets) == 0 {
|
||||
return results
|
||||
}
|
||||
|
||||
baseIDs := make([]string, 0, len(baseIDsSet))
|
||||
for id := range baseIDsSet {
|
||||
baseIDs = append(baseIDs, id)
|
||||
}
|
||||
|
||||
chunkMap := make(map[string]*types.Chunk, len(baseIDs))
|
||||
chunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, baseIDs)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "expand_list_base_failed", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return results
|
||||
}
|
||||
for _, chunk := range chunks {
|
||||
chunkMap[chunk.ID] = chunk
|
||||
}
|
||||
|
||||
neighborIDsSet := make(map[string]struct{})
|
||||
for _, chunk := range chunkMap {
|
||||
if chunk == nil {
|
||||
continue
|
||||
}
|
||||
if chunk.PreChunkID != "" {
|
||||
if _, exists := chunkMap[chunk.PreChunkID]; !exists {
|
||||
neighborIDsSet[chunk.PreChunkID] = struct{}{}
|
||||
}
|
||||
}
|
||||
if chunk.NextChunkID != "" {
|
||||
if _, exists := chunkMap[chunk.NextChunkID]; !exists {
|
||||
neighborIDsSet[chunk.NextChunkID] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(neighborIDsSet) > 0 {
|
||||
neighborIDs := make([]string, 0, len(neighborIDsSet))
|
||||
for id := range neighborIDsSet {
|
||||
neighborIDs = append(neighborIDs, id)
|
||||
}
|
||||
neighbors, err := p.chunkRepo.ListChunksByID(ctx, tenantID, neighborIDs)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "expand_list_neighbor_failed", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
} else {
|
||||
for _, chunk := range neighbors {
|
||||
chunkMap[chunk.ID] = chunk
|
||||
pipelineInfo(ctx, "Merge", "expand_list_neighbor_success", map[string]interface{}{
|
||||
"neighbor_chunk_id": chunk.ID,
|
||||
"neighbor_content": chunk.Content,
|
||||
"neighbor_chunk_type": chunk.ChunkType,
|
||||
"neighbor_len": runeLen(chunk.Content),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, target := range targets {
|
||||
res := target.result
|
||||
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, res.ID)
|
||||
baseChunk := chunkMap[res.ID]
|
||||
if baseChunk == nil || baseChunk.Content == "" || baseChunk.ChunkType != types.ChunkTypeText {
|
||||
continue
|
||||
}
|
||||
|
||||
prevContent := ""
|
||||
nextContent := ""
|
||||
prevIDs := []string{}
|
||||
nextIDs := []string{}
|
||||
|
||||
prevCursor := baseChunk.PreChunkID
|
||||
nextCursor := baseChunk.NextChunkID
|
||||
|
||||
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, prevCursor, nextCursor)
|
||||
|
||||
if prevCursor != "" {
|
||||
if prevChunk := chunkMap[prevCursor]; prevChunk != nil && prevChunk.KnowledgeID == baseChunk.KnowledgeID {
|
||||
prevContent = prevChunk.Content
|
||||
prevIDs = append(prevIDs, prevChunk.ID)
|
||||
prevCursor = prevChunk.PreChunkID
|
||||
} else {
|
||||
prevCursor = ""
|
||||
}
|
||||
}
|
||||
|
||||
if nextCursor != "" {
|
||||
if nextChunk := chunkMap[nextCursor]; nextChunk != nil && nextChunk.KnowledgeID == baseChunk.KnowledgeID {
|
||||
nextContent = nextChunk.Content
|
||||
nextIDs = append(nextIDs, nextChunk.ID)
|
||||
nextCursor = nextChunk.NextChunkID
|
||||
} else {
|
||||
nextCursor = ""
|
||||
}
|
||||
}
|
||||
|
||||
var merged string
|
||||
for {
|
||||
merged = mergeOrderedContent(prevContent, baseChunk.Content, nextContent, maxLen)
|
||||
if merged == "" {
|
||||
break
|
||||
}
|
||||
if runeLen(merged) >= minLen {
|
||||
break
|
||||
}
|
||||
if prevCursor == "" && nextCursor == "" {
|
||||
break
|
||||
}
|
||||
|
||||
expanded := false
|
||||
if prevCursor != "" {
|
||||
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, prevCursor)
|
||||
if prevChunk := chunkMap[prevCursor]; prevChunk != nil &&
|
||||
prevChunk.KnowledgeID == baseChunk.KnowledgeID {
|
||||
prevContent = concatNoOverlap(prevChunk.Content, prevContent)
|
||||
prevIDs = append([]string{prevChunk.ID}, prevIDs...)
|
||||
prevCursor = prevChunk.PreChunkID
|
||||
expanded = true
|
||||
} else {
|
||||
prevCursor = ""
|
||||
}
|
||||
}
|
||||
|
||||
merged = mergeOrderedContent(prevContent, baseChunk.Content, nextContent, maxLen)
|
||||
if runeLen(merged) >= minLen {
|
||||
break
|
||||
}
|
||||
|
||||
if nextCursor != "" {
|
||||
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, nextCursor)
|
||||
if nextChunk := chunkMap[nextCursor]; nextChunk != nil &&
|
||||
nextChunk.KnowledgeID == baseChunk.KnowledgeID {
|
||||
nextContent = concatNoOverlap(nextContent, nextChunk.Content)
|
||||
nextIDs = append(nextIDs, nextChunk.ID)
|
||||
nextCursor = nextChunk.NextChunkID
|
||||
expanded = true
|
||||
} else {
|
||||
nextCursor = ""
|
||||
}
|
||||
}
|
||||
|
||||
if !expanded {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if merged == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
beforeLen := runeLen(res.Content)
|
||||
res.Content = merged
|
||||
|
||||
for _, id := range prevIDs {
|
||||
if id != "" && !containsID(res.SubChunkID, id) {
|
||||
res.SubChunkID = append(res.SubChunkID, id)
|
||||
}
|
||||
}
|
||||
for _, id := range nextIDs {
|
||||
if id != "" && !containsID(res.SubChunkID, id) {
|
||||
res.SubChunkID = append(res.SubChunkID, id)
|
||||
}
|
||||
}
|
||||
|
||||
if prevContent != "" {
|
||||
res.StartAt = baseChunk.StartAt - runeLen(prevContent)
|
||||
if res.StartAt < 0 {
|
||||
res.StartAt = 0
|
||||
}
|
||||
}
|
||||
res.EndAt = res.StartAt + runeLen(res.Content)
|
||||
|
||||
pipelineInfo(ctx, "Merge", "expand_short_chunk", map[string]interface{}{
|
||||
"chunk_id": res.ID,
|
||||
"prev_ids": prevIDs,
|
||||
"next_ids": nextIDs,
|
||||
"before_len": beforeLen,
|
||||
"after_len": runeLen(res.Content),
|
||||
"base_content": baseChunk.Content,
|
||||
"after_content": res.Content,
|
||||
"chunk_type": res.ChunkType,
|
||||
"remaining_prev": prevCursor,
|
||||
"remaining_next": nextCursor,
|
||||
})
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// runeLen returns the length of a string in runes
|
||||
func runeLen(s string) int {
|
||||
return len([]rune(s))
|
||||
}
|
||||
|
||||
// mergeOrderedContent merges ordered content
|
||||
func mergeOrderedContent(prev, base, next string, maxLen int) string {
|
||||
content := base
|
||||
if prev != "" {
|
||||
content = concatNoOverlap(prev, content)
|
||||
}
|
||||
if next != "" {
|
||||
content = concatNoOverlap(content, next)
|
||||
}
|
||||
runes := []rune(content)
|
||||
if len(runes) > maxLen {
|
||||
return string(runes[:maxLen])
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
// concatNoOverlap concatenates two strings, removing potential overlapping prefix/suffix
|
||||
func concatNoOverlap(a, b string) string {
|
||||
if a == "" {
|
||||
return b
|
||||
}
|
||||
if b == "" {
|
||||
return a
|
||||
}
|
||||
|
||||
ar := []rune(a)
|
||||
br := []rune(b)
|
||||
maxOverlap := minInt(len(ar), len(br))
|
||||
for k := maxOverlap; k > 0; k-- {
|
||||
if string(ar[len(ar)-k:]) == string(br[:k]) {
|
||||
return string(ar) + string(br[k:])
|
||||
}
|
||||
}
|
||||
return string(ar) + string(br)
|
||||
}
|
||||
|
||||
func minInt(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func containsID(ids []string, target string) bool {
|
||||
for _, id := range ids {
|
||||
if id == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *PluginMerge) fetchChunksIfMissing(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
chunkMap map[string]*types.Chunk,
|
||||
chunkIDs ...string,
|
||||
) {
|
||||
missing := make([]string, 0, len(chunkIDs))
|
||||
for _, id := range chunkIDs {
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if _, exists := chunkMap[id]; !exists {
|
||||
missing = append(missing, id)
|
||||
}
|
||||
}
|
||||
if len(missing) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
chunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, missing)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "expand_fetch_missing_failed", map[string]interface{}{
|
||||
"missing_cnt": len(missing),
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
found := make(map[string]struct{}, len(chunks))
|
||||
for _, chunk := range chunks {
|
||||
chunkMap[chunk.ID] = chunk
|
||||
found[chunk.ID] = struct{}{}
|
||||
}
|
||||
|
||||
for _, id := range missing {
|
||||
if _, ok := found[id]; !ok {
|
||||
chunkMap[id] = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
package chatpipline
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// expandShortContextWithNeighbors expands the short context with neighbors
|
||||
func (p *PluginMerge) expandShortContextWithNeighbors(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
results []*types.SearchResult,
|
||||
) []*types.SearchResult {
|
||||
const (
|
||||
minLen = 350
|
||||
maxLen = 850
|
||||
)
|
||||
|
||||
if len(results) == 0 || p.chunkRepo == nil {
|
||||
return results
|
||||
}
|
||||
|
||||
tenantID, _ := types.TenantIDFromContext(ctx)
|
||||
if tenantID == 0 && chatManage != nil {
|
||||
tenantID = chatManage.TenantID
|
||||
}
|
||||
if tenantID == 0 {
|
||||
pipelineWarn(ctx, "Merge", "expand_skip", map[string]interface{}{
|
||||
"reason": "missing_tenant",
|
||||
})
|
||||
return results
|
||||
}
|
||||
|
||||
type targetInfo struct {
|
||||
result *types.SearchResult
|
||||
}
|
||||
|
||||
targets := make([]targetInfo, 0)
|
||||
baseIDsSet := make(map[string]struct{})
|
||||
|
||||
for _, r := range results {
|
||||
if r == nil || r.ID == "" || r.Content == "" {
|
||||
continue
|
||||
}
|
||||
if r.ChunkType != string(types.ChunkTypeText) {
|
||||
continue
|
||||
}
|
||||
if runeLen(r.Content) >= minLen {
|
||||
continue
|
||||
}
|
||||
targets = append(targets, targetInfo{result: r})
|
||||
baseIDsSet[r.ID] = struct{}{}
|
||||
pipelineInfo(ctx, "Merge", "need_expand", map[string]interface{}{
|
||||
"chunk_id": r.ID,
|
||||
"content": r.Content,
|
||||
"chunk_type": r.ChunkType,
|
||||
"len": runeLen(r.Content),
|
||||
})
|
||||
}
|
||||
|
||||
if len(targets) == 0 {
|
||||
return results
|
||||
}
|
||||
|
||||
baseIDs := make([]string, 0, len(baseIDsSet))
|
||||
for id := range baseIDsSet {
|
||||
baseIDs = append(baseIDs, id)
|
||||
}
|
||||
|
||||
chunkMap := make(map[string]*types.Chunk, len(baseIDs))
|
||||
chunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, baseIDs)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "expand_list_base_failed", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return results
|
||||
}
|
||||
for _, chunk := range chunks {
|
||||
chunkMap[chunk.ID] = chunk
|
||||
}
|
||||
|
||||
neighborIDsSet := make(map[string]struct{})
|
||||
for _, chunk := range chunkMap {
|
||||
if chunk == nil {
|
||||
continue
|
||||
}
|
||||
if chunk.PreChunkID != "" {
|
||||
if _, exists := chunkMap[chunk.PreChunkID]; !exists {
|
||||
neighborIDsSet[chunk.PreChunkID] = struct{}{}
|
||||
}
|
||||
}
|
||||
if chunk.NextChunkID != "" {
|
||||
if _, exists := chunkMap[chunk.NextChunkID]; !exists {
|
||||
neighborIDsSet[chunk.NextChunkID] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(neighborIDsSet) > 0 {
|
||||
neighborIDs := make([]string, 0, len(neighborIDsSet))
|
||||
for id := range neighborIDsSet {
|
||||
neighborIDs = append(neighborIDs, id)
|
||||
}
|
||||
neighbors, err := p.chunkRepo.ListChunksByID(ctx, tenantID, neighborIDs)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "expand_list_neighbor_failed", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
} else {
|
||||
for _, chunk := range neighbors {
|
||||
chunkMap[chunk.ID] = chunk
|
||||
pipelineInfo(ctx, "Merge", "expand_list_neighbor_success", map[string]interface{}{
|
||||
"neighbor_chunk_id": chunk.ID,
|
||||
"neighbor_content": chunk.Content,
|
||||
"neighbor_chunk_type": chunk.ChunkType,
|
||||
"neighbor_len": runeLen(chunk.Content),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, target := range targets {
|
||||
res := target.result
|
||||
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, res.ID)
|
||||
baseChunk := chunkMap[res.ID]
|
||||
if baseChunk == nil || baseChunk.Content == "" || baseChunk.ChunkType != types.ChunkTypeText {
|
||||
continue
|
||||
}
|
||||
|
||||
prevContent := ""
|
||||
nextContent := ""
|
||||
prevIDs := []string{}
|
||||
nextIDs := []string{}
|
||||
|
||||
prevCursor := baseChunk.PreChunkID
|
||||
nextCursor := baseChunk.NextChunkID
|
||||
|
||||
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, prevCursor, nextCursor)
|
||||
|
||||
if prevCursor != "" {
|
||||
if prevChunk := chunkMap[prevCursor]; prevChunk != nil && prevChunk.KnowledgeID == baseChunk.KnowledgeID {
|
||||
prevContent = prevChunk.Content
|
||||
prevIDs = append(prevIDs, prevChunk.ID)
|
||||
prevCursor = prevChunk.PreChunkID
|
||||
} else {
|
||||
prevCursor = ""
|
||||
}
|
||||
}
|
||||
|
||||
if nextCursor != "" {
|
||||
if nextChunk := chunkMap[nextCursor]; nextChunk != nil && nextChunk.KnowledgeID == baseChunk.KnowledgeID {
|
||||
nextContent = nextChunk.Content
|
||||
nextIDs = append(nextIDs, nextChunk.ID)
|
||||
nextCursor = nextChunk.NextChunkID
|
||||
} else {
|
||||
nextCursor = ""
|
||||
}
|
||||
}
|
||||
|
||||
var merged string
|
||||
for {
|
||||
merged = mergeOrderedContent(prevContent, baseChunk.Content, nextContent, maxLen)
|
||||
if merged == "" {
|
||||
break
|
||||
}
|
||||
if runeLen(merged) >= minLen {
|
||||
break
|
||||
}
|
||||
if prevCursor == "" && nextCursor == "" {
|
||||
break
|
||||
}
|
||||
|
||||
expanded := false
|
||||
if prevCursor != "" {
|
||||
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, prevCursor)
|
||||
if prevChunk := chunkMap[prevCursor]; prevChunk != nil &&
|
||||
prevChunk.KnowledgeID == baseChunk.KnowledgeID {
|
||||
prevContent = concatNoOverlap(prevChunk.Content, prevContent)
|
||||
prevIDs = append([]string{prevChunk.ID}, prevIDs...)
|
||||
prevCursor = prevChunk.PreChunkID
|
||||
expanded = true
|
||||
} else {
|
||||
prevCursor = ""
|
||||
}
|
||||
}
|
||||
|
||||
merged = mergeOrderedContent(prevContent, baseChunk.Content, nextContent, maxLen)
|
||||
if runeLen(merged) >= minLen {
|
||||
break
|
||||
}
|
||||
|
||||
if nextCursor != "" {
|
||||
p.fetchChunksIfMissing(ctx, tenantID, chunkMap, nextCursor)
|
||||
if nextChunk := chunkMap[nextCursor]; nextChunk != nil &&
|
||||
nextChunk.KnowledgeID == baseChunk.KnowledgeID {
|
||||
nextContent = concatNoOverlap(nextContent, nextChunk.Content)
|
||||
nextIDs = append(nextIDs, nextChunk.ID)
|
||||
nextCursor = nextChunk.NextChunkID
|
||||
expanded = true
|
||||
} else {
|
||||
nextCursor = ""
|
||||
}
|
||||
}
|
||||
|
||||
if !expanded {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if merged == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
beforeLen := runeLen(res.Content)
|
||||
res.Content = merged
|
||||
|
||||
for _, id := range prevIDs {
|
||||
if id != "" && !containsID(res.SubChunkID, id) {
|
||||
res.SubChunkID = append(res.SubChunkID, id)
|
||||
}
|
||||
}
|
||||
for _, id := range nextIDs {
|
||||
if id != "" && !containsID(res.SubChunkID, id) {
|
||||
res.SubChunkID = append(res.SubChunkID, id)
|
||||
}
|
||||
}
|
||||
|
||||
if prevContent != "" {
|
||||
res.StartAt = baseChunk.StartAt - runeLen(prevContent)
|
||||
if res.StartAt < 0 {
|
||||
res.StartAt = 0
|
||||
}
|
||||
}
|
||||
res.EndAt = res.StartAt + runeLen(res.Content)
|
||||
|
||||
pipelineInfo(ctx, "Merge", "expand_short_chunk", map[string]interface{}{
|
||||
"chunk_id": res.ID,
|
||||
"prev_ids": prevIDs,
|
||||
"next_ids": nextIDs,
|
||||
"before_len": beforeLen,
|
||||
"after_len": runeLen(res.Content),
|
||||
"base_content": baseChunk.Content,
|
||||
"after_content": res.Content,
|
||||
"chunk_type": res.ChunkType,
|
||||
"remaining_prev": prevCursor,
|
||||
"remaining_next": nextCursor,
|
||||
})
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
// runeLen returns the length of a string in runes
|
||||
func runeLen(s string) int {
|
||||
return len([]rune(s))
|
||||
}
|
||||
|
||||
// mergeOrderedContent merges ordered content
|
||||
func mergeOrderedContent(prev, base, next string, maxLen int) string {
|
||||
content := base
|
||||
if prev != "" {
|
||||
content = concatNoOverlap(prev, content)
|
||||
}
|
||||
if next != "" {
|
||||
content = concatNoOverlap(content, next)
|
||||
}
|
||||
runes := []rune(content)
|
||||
if len(runes) > maxLen {
|
||||
return string(runes[:maxLen])
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
// concatNoOverlap concatenates two strings, removing potential overlapping prefix/suffix
|
||||
func concatNoOverlap(a, b string) string {
|
||||
if a == "" {
|
||||
return b
|
||||
}
|
||||
if b == "" {
|
||||
return a
|
||||
}
|
||||
|
||||
ar := []rune(a)
|
||||
br := []rune(b)
|
||||
maxOverlap := minInt(len(ar), len(br))
|
||||
for k := maxOverlap; k > 0; k-- {
|
||||
if string(ar[len(ar)-k:]) == string(br[:k]) {
|
||||
return string(ar) + string(br[k:])
|
||||
}
|
||||
}
|
||||
return string(ar) + string(br)
|
||||
}
|
||||
|
||||
func minInt(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func containsID(ids []string, target string) bool {
|
||||
for _, id := range ids {
|
||||
if id == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *PluginMerge) fetchChunksIfMissing(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
chunkMap map[string]*types.Chunk,
|
||||
chunkIDs ...string,
|
||||
) {
|
||||
missing := make([]string, 0, len(chunkIDs))
|
||||
for _, id := range chunkIDs {
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if _, exists := chunkMap[id]; !exists {
|
||||
missing = append(missing, id)
|
||||
}
|
||||
}
|
||||
if len(missing) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
chunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, missing)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "expand_fetch_missing_failed", map[string]interface{}{
|
||||
"missing_cnt": len(missing),
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
|
||||
found := make(map[string]struct{}, len(chunks))
|
||||
for _, chunk := range chunks {
|
||||
chunkMap[chunk.ID] = chunk
|
||||
found[chunk.ID] = struct{}{}
|
||||
}
|
||||
|
||||
for _, id := range missing {
|
||||
if _, ok := found[id]; !ok {
|
||||
chunkMap[id] = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package chatpipline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// populateFAQAnswers populates FAQ answers for the search results
|
||||
func (p *PluginMerge) populateFAQAnswers(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
results []*types.SearchResult,
|
||||
) []*types.SearchResult {
|
||||
if len(results) == 0 || p.chunkRepo == nil {
|
||||
return results
|
||||
}
|
||||
|
||||
tenantID, _ := types.TenantIDFromContext(ctx)
|
||||
if tenantID == 0 && chatManage != nil {
|
||||
tenantID = chatManage.TenantID
|
||||
}
|
||||
if tenantID == 0 {
|
||||
pipelineWarn(ctx, "Merge", "faq_enrich_skip", map[string]interface{}{
|
||||
"reason": "missing_tenant",
|
||||
})
|
||||
return results
|
||||
}
|
||||
|
||||
chunkResultMap := make(map[string][]*types.SearchResult)
|
||||
chunkIDSet := make(map[string]struct{})
|
||||
for _, r := range results {
|
||||
if r == nil || r.ID == "" {
|
||||
continue
|
||||
}
|
||||
if r.ChunkType != string(types.ChunkTypeFAQ) {
|
||||
continue
|
||||
}
|
||||
chunkResultMap[r.ID] = append(chunkResultMap[r.ID], r)
|
||||
if _, exists := chunkIDSet[r.ID]; !exists {
|
||||
chunkIDSet[r.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
if len(chunkIDSet) == 0 {
|
||||
return results
|
||||
}
|
||||
|
||||
chunkIDs := make([]string, 0, len(chunkIDSet))
|
||||
for id := range chunkIDSet {
|
||||
chunkIDs = append(chunkIDs, id)
|
||||
}
|
||||
|
||||
chunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "faq_chunk_fetch_failed", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return results
|
||||
}
|
||||
|
||||
updated := 0
|
||||
for _, chunk := range chunks {
|
||||
if chunk == nil {
|
||||
continue
|
||||
}
|
||||
meta, err := chunk.FAQMetadata()
|
||||
if err != nil || meta == nil {
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "faq_metadata_parse_failed", map[string]interface{}{
|
||||
"chunk_id": chunk.ID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
content := buildFAQAnswerContent(meta)
|
||||
if content == "" {
|
||||
continue
|
||||
}
|
||||
for _, r := range chunkResultMap[chunk.ID] {
|
||||
if r == nil {
|
||||
continue
|
||||
}
|
||||
r.Content = content
|
||||
updated++
|
||||
}
|
||||
}
|
||||
|
||||
if updated > 0 {
|
||||
pipelineInfo(ctx, "Merge", "faq_content_enriched", map[string]interface{}{
|
||||
"chunk_cnt": updated,
|
||||
})
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
// buildFAQAnswerContent builds the content of a FAQ answer
|
||||
func buildFAQAnswerContent(meta *types.FAQChunkMetadata) string {
|
||||
if meta == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
question := strings.TrimSpace(meta.StandardQuestion)
|
||||
answers := make([]string, 0, len(meta.Answers))
|
||||
for _, ans := range meta.Answers {
|
||||
if trimmed := strings.TrimSpace(ans); trimmed != "" {
|
||||
answers = append(answers, trimmed)
|
||||
}
|
||||
}
|
||||
|
||||
if question == "" && len(answers) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
if question != "" {
|
||||
builder.WriteString("Q: ")
|
||||
builder.WriteString(question)
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
|
||||
if len(answers) > 0 {
|
||||
builder.WriteString("Answer:\n")
|
||||
for _, ans := range answers {
|
||||
builder.WriteString("- ")
|
||||
builder.WriteString(ans)
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
return strings.TrimSpace(builder.String())
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package chatpipline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/searchutil"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// filterHistoryResults retrieves history references and filters them by
|
||||
// textual similarity to the current query. Only references that are above
|
||||
// a Jaccard similarity threshold are kept, and their scores are discounted
|
||||
// to reflect that they were not directly retrieved for the current query.
|
||||
// Results already present in currentResults (by chunk ID) are excluded.
|
||||
func filterHistoryResults(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
currentResults []*types.SearchResult,
|
||||
) []*types.SearchResult {
|
||||
const (
|
||||
// minSimilarity is the minimum Jaccard similarity between the current
|
||||
// query and a history chunk's content for it to be injected.
|
||||
minSimilarity = 0.15
|
||||
// historyScoreDiscount reduces the original score of history results
|
||||
// to rank them below freshly-retrieved results of similar relevance.
|
||||
historyScoreDiscount = 0.6
|
||||
// maxHistoryResults caps the number of history results injected to
|
||||
// avoid overwhelming the context with stale references.
|
||||
maxHistoryResults = 3
|
||||
)
|
||||
|
||||
raw := getSearchResultFromHistory(chatManage)
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Build a set of chunk IDs already in current results for fast dedup
|
||||
existingIDs := make(map[string]struct{}, len(currentResults))
|
||||
for _, r := range currentResults {
|
||||
existingIDs[r.ID] = struct{}{}
|
||||
}
|
||||
|
||||
// Use RewriteQuery if available (it's the cleaned-up retrieval query),
|
||||
// otherwise fall back to the original query.
|
||||
query := chatManage.RewriteQuery
|
||||
if query == "" {
|
||||
query = chatManage.Query
|
||||
}
|
||||
queryTokens := searchutil.TokenizeSimple(query)
|
||||
|
||||
var filtered []*types.SearchResult
|
||||
for _, r := range raw {
|
||||
if _, exists := existingIDs[r.ID]; exists {
|
||||
continue
|
||||
}
|
||||
contentTokens := searchutil.TokenizeSimple(r.Content)
|
||||
sim := searchutil.Jaccard(queryTokens, contentTokens)
|
||||
if sim < minSimilarity {
|
||||
pipelineInfo(ctx, "Merge", "history_filter_drop", map[string]interface{}{
|
||||
"chunk_id": r.ID,
|
||||
"similarity": sim,
|
||||
})
|
||||
continue
|
||||
}
|
||||
r.MatchType = types.MatchTypeHistory
|
||||
r.Score = r.Score * historyScoreDiscount
|
||||
r.Metadata = ensureMetadata(r.Metadata)
|
||||
r.Metadata["history_similarity"] = strings.TrimRight(strings.TrimRight(
|
||||
fmt.Sprintf("%.4f", sim), "0"), ".")
|
||||
filtered = append(filtered, r)
|
||||
|
||||
pipelineInfo(ctx, "Merge", "history_filter_keep", map[string]interface{}{
|
||||
"chunk_id": r.ID,
|
||||
"similarity": sim,
|
||||
"new_score": r.Score,
|
||||
})
|
||||
|
||||
if len(filtered) >= maxHistoryResults {
|
||||
break
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package chatpipline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// mergeOverlappingChunks merges chunks with overlapping or adjacent StartAt/EndAt
|
||||
// ranges within a single knowledge source group. Chunks MUST be pre-sorted by
|
||||
// StartAt ascending, EndAt ascending. The highest score among merged chunks is kept.
|
||||
func (p *PluginMerge) mergeOverlappingChunks(
|
||||
ctx context.Context,
|
||||
knowledgeID string,
|
||||
chunks []*types.SearchResult,
|
||||
) []*types.SearchResult {
|
||||
if len(chunks) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
merged := []*types.SearchResult{chunks[0]}
|
||||
for i := 1; i < len(chunks); i++ {
|
||||
lastChunk := merged[len(merged)-1]
|
||||
|
||||
// Non-overlapping: add as a new entry
|
||||
if chunks[i].StartAt > lastChunk.EndAt {
|
||||
merged = append(merged, chunks[i])
|
||||
continue
|
||||
}
|
||||
|
||||
// Partial overlap: append the non-overlapping suffix
|
||||
if chunks[i].EndAt > lastChunk.EndAt {
|
||||
contentRunes := []rune(chunks[i].Content)
|
||||
offset := len(contentRunes) - (chunks[i].EndAt - lastChunk.EndAt)
|
||||
lastChunk.Content = lastChunk.Content + string(contentRunes[offset:])
|
||||
lastChunk.EndAt = chunks[i].EndAt
|
||||
lastChunk.SubChunkID = append(lastChunk.SubChunkID, chunks[i].ID)
|
||||
|
||||
if err := mergeImageInfo(ctx, lastChunk, chunks[i]); err != nil {
|
||||
pipelineWarn(ctx, "Merge", "image_merge", map[string]interface{}{
|
||||
"knowledge_id": knowledgeID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Fully contained: track the subsumed chunk and merge its ImageInfo
|
||||
if !containsID(lastChunk.SubChunkID, chunks[i].ID) {
|
||||
lastChunk.SubChunkID = append(lastChunk.SubChunkID, chunks[i].ID)
|
||||
}
|
||||
if err := mergeImageInfo(ctx, lastChunk, chunks[i]); err != nil {
|
||||
pipelineWarn(ctx, "Merge", "image_merge_contained", map[string]interface{}{
|
||||
"knowledge_id": knowledgeID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the higher score
|
||||
if chunks[i].Score > lastChunk.Score {
|
||||
lastChunk.Score = chunks[i].Score
|
||||
}
|
||||
}
|
||||
|
||||
// Sort merged chunks by score (highest first)
|
||||
sort.Slice(merged, func(i, j int) bool {
|
||||
return merged[i].Score > merged[j].Score
|
||||
})
|
||||
|
||||
return merged
|
||||
}
|
||||
|
||||
// mergeImageInfo merges ImageInfo from source into target, deduplicating by URL.
|
||||
func mergeImageInfo(ctx context.Context, target *types.SearchResult, source *types.SearchResult) error {
|
||||
if source.ImageInfo == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var sourceImageInfos []types.ImageInfo
|
||||
if err := json.Unmarshal([]byte(source.ImageInfo), &sourceImageInfos); err != nil {
|
||||
pipelineWarn(ctx, "Merge", "image_unmarshal_source", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
if len(sourceImageInfos) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var targetImageInfos []types.ImageInfo
|
||||
if target.ImageInfo != "" {
|
||||
if err := json.Unmarshal([]byte(target.ImageInfo), &targetImageInfos); err != nil {
|
||||
pipelineWarn(ctx, "Merge", "image_unmarshal_target", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
target.ImageInfo = source.ImageInfo
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
targetImageInfos = append(targetImageInfos, sourceImageInfos...)
|
||||
|
||||
uniqueMap := make(map[string]bool)
|
||||
uniqueImageInfos := make([]types.ImageInfo, 0, len(targetImageInfos))
|
||||
|
||||
for _, imgInfo := range targetImageInfos {
|
||||
if imgInfo.URL != "" && !uniqueMap[imgInfo.URL] {
|
||||
uniqueMap[imgInfo.URL] = true
|
||||
uniqueImageInfos = append(uniqueImageInfos, imgInfo)
|
||||
}
|
||||
}
|
||||
|
||||
mergedImageInfoJSON, err := json.Marshal(uniqueImageInfos)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Merge", "image_marshal", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
target.ImageInfo = string(mergedImageInfoJSON)
|
||||
pipelineInfo(ctx, "Merge", "image_merged", map[string]interface{}{
|
||||
"image_refs": len(uniqueImageInfos),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,253 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service/retriever"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/embedding"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// GetQueryEmbedding computes the query embedding using the embedding model
|
||||
// associated with the given knowledge base. Callers can pre-compute and reuse
|
||||
// the result across multiple KBs that share the same embedding model to avoid
|
||||
// redundant embedding API calls.
|
||||
func (s *knowledgeBaseService) GetQueryEmbedding(ctx context.Context, kbID string, queryText string) ([]float32, error) {
|
||||
kb, err := s.repo.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
currentTenantID := types.MustTenantIDFromContext(ctx)
|
||||
var embeddingModel embedding.Embedder
|
||||
|
||||
if kb.TenantID != currentTenantID {
|
||||
embeddingModel, err = s.modelService.GetEmbeddingModelForTenant(ctx, kb.EmbeddingModelID, kb.TenantID)
|
||||
} else {
|
||||
embeddingModel, err = s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
}
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "GetQueryEmbedding: failed to get embedding model %s: %v", kb.EmbeddingModelID, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return embeddingModel.Embed(ctx, queryText)
|
||||
}
|
||||
|
||||
// ResolveEmbeddingModelKeys resolves embedding model IDs to their actual model
|
||||
// identity key (name + endpoint). KBs using the same underlying model across
|
||||
// different tenants will share the same key, enabling optimal grouping.
|
||||
func (s *knowledgeBaseService) ResolveEmbeddingModelKeys(ctx context.Context, kbs []*types.KnowledgeBase) map[string]string {
|
||||
type modelRef struct {
|
||||
ModelID string
|
||||
TenantID uint64
|
||||
}
|
||||
|
||||
// Deduplicate model references
|
||||
uniqueRefs := make(map[modelRef]struct{})
|
||||
kbRefs := make(map[string]modelRef, len(kbs))
|
||||
for _, kb := range kbs {
|
||||
ref := modelRef{ModelID: kb.EmbeddingModelID, TenantID: kb.TenantID}
|
||||
uniqueRefs[ref] = struct{}{}
|
||||
kbRefs[kb.ID] = ref
|
||||
}
|
||||
|
||||
// Resolve each unique (modelID, tenantID) to a model identity key
|
||||
resolvedKeys := make(map[modelRef]string, len(uniqueRefs))
|
||||
for ref := range uniqueRefs {
|
||||
tenantCtx := context.WithValue(ctx, types.TenantIDContextKey, ref.TenantID)
|
||||
model, err := s.modelService.GetModelByID(tenantCtx, ref.ModelID)
|
||||
if err != nil || model == nil {
|
||||
logger.Warnf(ctx, "ResolveEmbeddingModelKeys: cannot resolve model %s for tenant %d: %v", ref.ModelID, ref.TenantID, err)
|
||||
resolvedKeys[ref] = ref.ModelID
|
||||
continue
|
||||
}
|
||||
resolvedKeys[ref] = model.Name + "|" + model.Parameters.BaseURL
|
||||
}
|
||||
|
||||
result := make(map[string]string, len(kbs))
|
||||
for _, kb := range kbs {
|
||||
result[kb.ID] = resolvedKeys[kbRefs[kb.ID]]
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// HybridSearch performs hybrid search, including vector retrieval and keyword retrieval.
|
||||
//
|
||||
// id is the "primary" knowledge base ID used to resolve the embedding model and
|
||||
// determine the KB type (e.g. FAQ). When params.KnowledgeBaseIDs is set, those
|
||||
// IDs are used for the actual retrieval scope instead of id alone, allowing a
|
||||
// single call to span multiple KBs that share the same embedding model. In that
|
||||
// case id should be any one of those KBs (typically the first) so that its
|
||||
// embedding model and type configuration are used for the search.
|
||||
func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
||||
id string,
|
||||
params types.SearchParams,
|
||||
) ([]*types.SearchResult, error) {
|
||||
// Determine the set of KB IDs to search
|
||||
searchKBIDs := params.KnowledgeBaseIDs
|
||||
if len(searchKBIDs) == 0 {
|
||||
searchKBIDs = []string{id}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Hybrid search parameters, knowledge base IDs: %v, query text: %s", searchKBIDs, params.QueryText)
|
||||
|
||||
tenantInfo, _ := types.TenantInfoFromContext(ctx)
|
||||
|
||||
// Create a composite retrieval engine with tenant's configured retrievers
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.GetEffectiveEngines())
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create retrieval engine: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
kb, err := s.repo.GetKnowledgeBaseByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_base_id": id,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Use 5x over-retrieval to ensure sufficient candidates for RRF fusion and reranking.
|
||||
// Scale proportionally when searching multiple KBs to maintain per-KB recall quality.
|
||||
matchCount := max(params.MatchCount*5, 50) * len(searchKBIDs)
|
||||
if matchCount > 1000 {
|
||||
matchCount = 1000
|
||||
}
|
||||
|
||||
// Build retrieval parameters for vector and keyword engines
|
||||
retrieveParams, err := s.buildRetrievalParams(ctx, retrieveEngine, kb, params, searchKBIDs, matchCount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(retrieveParams) == 0 {
|
||||
logger.Error(ctx, "No retrieval parameters available")
|
||||
return nil, errors.New("no retrieve params")
|
||||
}
|
||||
|
||||
// Execute retrieval using the configured engines
|
||||
logger.Infof(ctx, "Starting retrieval, parameter count: %d", len(retrieveParams))
|
||||
retrieveResults, err := retrieveEngine.Retrieve(ctx, retrieveParams)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_base_ids": searchKBIDs,
|
||||
"query_text": params.QueryText,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Separate and fuse retrieval results
|
||||
vectorResults, keywordResults := classifyRetrievalResults(ctx, retrieveResults)
|
||||
if len(vectorResults) == 0 && len(keywordResults) == 0 {
|
||||
logger.Info(ctx, "No search results found")
|
||||
return nil, nil
|
||||
}
|
||||
logger.Infof(ctx, "Result count before fusion: vector=%d, keyword=%d", len(vectorResults), len(keywordResults))
|
||||
|
||||
deduplicatedChunks := fuseOrDeduplicate(ctx, vectorResults, keywordResults)
|
||||
|
||||
kb.EnsureDefaults()
|
||||
|
||||
// FAQ-specific post-processing: iterative retrieval or negative question filtering
|
||||
deduplicatedChunks = s.applyFAQPostProcessing(ctx, kb, deduplicatedChunks, vectorResults, retrieveEngine, retrieveParams, params, matchCount)
|
||||
|
||||
// Limit to MatchCount
|
||||
if len(deduplicatedChunks) > params.MatchCount {
|
||||
deduplicatedChunks = deduplicatedChunks[:params.MatchCount]
|
||||
}
|
||||
|
||||
return s.processSearchResults(ctx, deduplicatedChunks, params.SkipContextEnrichment)
|
||||
}
|
||||
|
||||
// buildRetrievalParams constructs the vector and keyword retrieval parameters
|
||||
// based on the knowledge base type, engine capabilities, and search params.
|
||||
func (s *knowledgeBaseService) buildRetrievalParams(
|
||||
ctx context.Context,
|
||||
retrieveEngine *retriever.CompositeRetrieveEngine,
|
||||
kb *types.KnowledgeBase,
|
||||
params types.SearchParams,
|
||||
searchKBIDs []string,
|
||||
matchCount int,
|
||||
) ([]types.RetrieveParams, error) {
|
||||
currentTenantID := types.MustTenantIDFromContext(ctx)
|
||||
var retrieveParams []types.RetrieveParams
|
||||
|
||||
// Add vector retrieval params if supported
|
||||
if retrieveEngine.SupportRetriever(types.VectorRetrieverType) && !params.DisableVectorMatch {
|
||||
logger.Info(ctx, "Vector retrieval supported, preparing vector retrieval parameters")
|
||||
|
||||
var queryEmbedding []float32
|
||||
|
||||
if len(params.QueryEmbedding) > 0 {
|
||||
queryEmbedding = params.QueryEmbedding
|
||||
logger.Infof(ctx, "Using pre-computed query embedding, vector length: %d", len(queryEmbedding))
|
||||
} else {
|
||||
logger.Infof(ctx, "Getting embedding model, model ID: %s", kb.EmbeddingModelID)
|
||||
|
||||
// Check if this is a cross-tenant shared knowledge base
|
||||
// For shared KB, we must use the source tenant's embedding model to ensure vector compatibility
|
||||
var embeddingModel embedding.Embedder
|
||||
var err error
|
||||
if kb.TenantID != currentTenantID {
|
||||
logger.Infof(ctx, "Cross-tenant knowledge base detected, using source tenant's embedding model. KB tenant: %d, current tenant: %d", kb.TenantID, currentTenantID)
|
||||
embeddingModel, err = s.modelService.GetEmbeddingModelForTenant(ctx, kb.EmbeddingModelID, kb.TenantID)
|
||||
} else {
|
||||
embeddingModel, err = s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get embedding model, model ID: %s, error: %v", kb.EmbeddingModelID, err)
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "Embedding model retrieved: %v", embeddingModel)
|
||||
|
||||
logger.Info(ctx, "Starting to generate query embedding")
|
||||
queryEmbedding, err = embeddingModel.Embed(ctx, params.QueryText)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to embed query text, query text: %s, error: %v", params.QueryText, err)
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "Query embedding generated successfully, embedding vector length: %d", len(queryEmbedding))
|
||||
}
|
||||
|
||||
vectorParams := types.RetrieveParams{
|
||||
Query: params.QueryText,
|
||||
Embedding: queryEmbedding,
|
||||
KnowledgeBaseIDs: searchKBIDs,
|
||||
TopK: matchCount,
|
||||
Threshold: params.VectorThreshold,
|
||||
RetrieverType: types.VectorRetrieverType,
|
||||
KnowledgeIDs: params.KnowledgeIDs,
|
||||
TagIDs: params.TagIDs,
|
||||
}
|
||||
|
||||
// For FAQ knowledge base, use FAQ index
|
||||
if kb.Type == types.KnowledgeBaseTypeFAQ {
|
||||
vectorParams.KnowledgeType = types.KnowledgeTypeFAQ
|
||||
}
|
||||
|
||||
retrieveParams = append(retrieveParams, vectorParams)
|
||||
logger.Info(ctx, "Vector retrieval parameters setup completed")
|
||||
}
|
||||
|
||||
// Add keyword retrieval params if supported and not FAQ
|
||||
if retrieveEngine.SupportRetriever(types.KeywordsRetrieverType) && !params.DisableKeywordsMatch &&
|
||||
kb.Type != types.KnowledgeBaseTypeFAQ {
|
||||
logger.Info(ctx, "Keyword retrieval supported, preparing keyword retrieval parameters")
|
||||
retrieveParams = append(retrieveParams, types.RetrieveParams{
|
||||
Query: params.QueryText,
|
||||
KnowledgeBaseIDs: searchKBIDs,
|
||||
TopK: matchCount,
|
||||
Threshold: params.KeywordThreshold,
|
||||
RetrieverType: types.KeywordsRetrieverType,
|
||||
KnowledgeIDs: params.KnowledgeIDs,
|
||||
TagIDs: params.TagIDs,
|
||||
})
|
||||
logger.Info(ctx, "Keyword retrieval parameters setup completed")
|
||||
}
|
||||
|
||||
return retrieveParams, nil
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service/retriever"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// applyFAQPostProcessing handles FAQ-specific post-processing: iterative retrieval
|
||||
// when not enough unique chunks are found, or negative question filtering otherwise.
|
||||
// For non-FAQ knowledge bases, returns the input unchanged.
|
||||
func (s *knowledgeBaseService) applyFAQPostProcessing(
|
||||
ctx context.Context,
|
||||
kb *types.KnowledgeBase,
|
||||
chunks []*types.IndexWithScore,
|
||||
vectorResults []*types.IndexWithScore,
|
||||
retrieveEngine *retriever.CompositeRetrieveEngine,
|
||||
retrieveParams []types.RetrieveParams,
|
||||
params types.SearchParams,
|
||||
matchCount int,
|
||||
) []*types.IndexWithScore {
|
||||
if kb.Type != types.KnowledgeBaseTypeFAQ {
|
||||
return chunks
|
||||
}
|
||||
|
||||
// Check if we need iterative retrieval for FAQ with separate indexing
|
||||
// Only use iterative retrieval if we don't have enough unique chunks after first deduplication
|
||||
needsIterativeRetrieval := len(chunks) < params.MatchCount && len(vectorResults) == matchCount
|
||||
if needsIterativeRetrieval {
|
||||
logger.Info(ctx, "Not enough unique chunks, using iterative retrieval for FAQ")
|
||||
return s.iterativeRetrieveWithDeduplication(
|
||||
ctx,
|
||||
retrieveEngine,
|
||||
retrieveParams,
|
||||
params.MatchCount,
|
||||
params.QueryText,
|
||||
)
|
||||
}
|
||||
|
||||
// Filter by negative questions if not using iterative retrieval
|
||||
result := s.filterByNegativeQuestions(ctx, chunks, params.QueryText)
|
||||
logger.Infof(ctx, "Result count after negative question filtering: %d", len(result))
|
||||
return result
|
||||
}
|
||||
|
||||
// iterativeRetrieveWithDeduplication performs iterative retrieval until enough unique chunks are found.
|
||||
// This is used for FAQ knowledge bases with separate indexing mode.
|
||||
// Negative question filtering is applied after each iteration with chunk data caching.
|
||||
func (s *knowledgeBaseService) iterativeRetrieveWithDeduplication(ctx context.Context,
|
||||
retrieveEngine *retriever.CompositeRetrieveEngine,
|
||||
retrieveParams []types.RetrieveParams,
|
||||
matchCount int,
|
||||
queryText string,
|
||||
) []*types.IndexWithScore {
|
||||
maxIterations := 5
|
||||
// Start with a larger TopK since we're called when first retrieval wasn't enough
|
||||
// The first retrieval already used matchCount*3, so start from there
|
||||
currentTopK := matchCount * 3
|
||||
uniqueChunks := make(map[string]*types.IndexWithScore)
|
||||
// Cache chunk data to avoid repeated DB queries across iterations
|
||||
chunkDataCache := make(map[string]*types.Chunk)
|
||||
// Track chunks that have been filtered out by negative questions
|
||||
filteredOutChunks := make(map[string]struct{})
|
||||
|
||||
queryTextLower := strings.ToLower(strings.TrimSpace(queryText))
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
|
||||
for i := 0; i < maxIterations; i++ {
|
||||
// Update TopK in retrieve params
|
||||
updatedParams := make([]types.RetrieveParams, len(retrieveParams))
|
||||
for j := range retrieveParams {
|
||||
updatedParams[j] = retrieveParams[j]
|
||||
updatedParams[j].TopK = currentTopK
|
||||
}
|
||||
|
||||
// Execute retrieval
|
||||
retrieveResults, err := retrieveEngine.Retrieve(ctx, updatedParams)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Iterative retrieval failed at iteration %d: %v", i+1, err)
|
||||
break
|
||||
}
|
||||
|
||||
// Collect results
|
||||
iterationResults := []*types.IndexWithScore{}
|
||||
for _, retrieveResult := range retrieveResults {
|
||||
iterationResults = append(iterationResults, retrieveResult.Results...)
|
||||
}
|
||||
|
||||
if len(iterationResults) == 0 {
|
||||
logger.Infof(ctx, "No results found at iteration %d", i+1)
|
||||
break
|
||||
}
|
||||
|
||||
totalRetrieved := len(iterationResults)
|
||||
|
||||
// Collect new chunk IDs that need to be fetched from DB
|
||||
newChunkIDs := make([]string, 0)
|
||||
for _, result := range iterationResults {
|
||||
if _, cached := chunkDataCache[result.ChunkID]; !cached {
|
||||
if _, filtered := filteredOutChunks[result.ChunkID]; !filtered {
|
||||
newChunkIDs = append(newChunkIDs, result.ChunkID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Batch fetch only new chunks
|
||||
if len(newChunkIDs) > 0 {
|
||||
newChunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, newChunkIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to fetch chunks at iteration %d: %v", i+1, err)
|
||||
} else {
|
||||
for _, chunk := range newChunks {
|
||||
chunkDataCache[chunk.ID] = chunk
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Deduplicate, merge, and filter in one pass
|
||||
for _, result := range iterationResults {
|
||||
// Skip if already filtered out
|
||||
if _, filtered := filteredOutChunks[result.ChunkID]; filtered {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check negative questions using cached data
|
||||
if chunkData, ok := chunkDataCache[result.ChunkID]; ok {
|
||||
if chunkData.ChunkType == types.ChunkTypeFAQ {
|
||||
if meta, err := chunkData.FAQMetadata(); err == nil && meta != nil {
|
||||
if s.matchesNegativeQuestions(queryTextLower, meta.NegativeQuestions) {
|
||||
filteredOutChunks[result.ChunkID] = struct{}{}
|
||||
delete(uniqueChunks, result.ChunkID)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep highest score for each chunk
|
||||
if existing, ok := uniqueChunks[result.ChunkID]; !ok || result.Score > existing.Score {
|
||||
uniqueChunks[result.ChunkID] = result
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"After iteration %d: retrieved %d results, found %d valid unique chunks (target: %d)",
|
||||
i+1,
|
||||
totalRetrieved,
|
||||
len(uniqueChunks),
|
||||
matchCount,
|
||||
)
|
||||
|
||||
// Early stop: Check if we have enough unique chunks after deduplication and filtering
|
||||
if len(uniqueChunks) >= matchCount {
|
||||
logger.Infof(ctx, "Found enough unique chunks after %d iterations", i+1)
|
||||
break
|
||||
}
|
||||
|
||||
// Early stop: If we got fewer results than TopK, there are no more results to retrieve
|
||||
if totalRetrieved < currentTopK {
|
||||
logger.Infof(ctx, "No more results available (got %d < %d), stopping iteration", totalRetrieved, currentTopK)
|
||||
break
|
||||
}
|
||||
|
||||
// Increase TopK for next iteration
|
||||
currentTopK *= 2
|
||||
}
|
||||
|
||||
// Convert map to slice and sort by score
|
||||
result := make([]*types.IndexWithScore, 0, len(uniqueChunks))
|
||||
for _, chunk := range uniqueChunks {
|
||||
result = append(result, chunk)
|
||||
}
|
||||
|
||||
slices.SortFunc(result, sortByScoreDesc)
|
||||
|
||||
logger.Infof(ctx, "Iterative retrieval completed: %d unique chunks found after filtering", len(result))
|
||||
return result
|
||||
}
|
||||
|
||||
// filterByNegativeQuestions filters out chunks that match negative questions for FAQ knowledge bases.
|
||||
func (s *knowledgeBaseService) filterByNegativeQuestions(ctx context.Context,
|
||||
chunks []*types.IndexWithScore,
|
||||
queryText string,
|
||||
) []*types.IndexWithScore {
|
||||
if len(chunks) == 0 {
|
||||
return chunks
|
||||
}
|
||||
|
||||
queryTextLower := strings.ToLower(strings.TrimSpace(queryText))
|
||||
if queryTextLower == "" {
|
||||
return chunks
|
||||
}
|
||||
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
|
||||
// Collect chunk IDs
|
||||
chunkIDs := make([]string, 0, len(chunks))
|
||||
for _, chunk := range chunks {
|
||||
chunkIDs = append(chunkIDs, chunk.ChunkID)
|
||||
}
|
||||
|
||||
// Batch fetch chunks to get negative questions
|
||||
allChunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to fetch chunks for negative question filtering: %v", err)
|
||||
// If we can't fetch chunks, return original results
|
||||
return chunks
|
||||
}
|
||||
|
||||
// Build chunk map for quick lookup
|
||||
chunkMap := make(map[string]*types.Chunk, len(allChunks))
|
||||
for _, chunk := range allChunks {
|
||||
chunkMap[chunk.ID] = chunk
|
||||
}
|
||||
|
||||
// Filter out chunks that match negative questions
|
||||
filteredChunks := make([]*types.IndexWithScore, 0, len(chunks))
|
||||
for _, chunk := range chunks {
|
||||
chunkData, ok := chunkMap[chunk.ChunkID]
|
||||
if !ok {
|
||||
// If chunk not found, keep it (shouldn't happen, but be safe)
|
||||
filteredChunks = append(filteredChunks, chunk)
|
||||
continue
|
||||
}
|
||||
|
||||
// Only filter FAQ type chunks
|
||||
if chunkData.ChunkType != types.ChunkTypeFAQ {
|
||||
filteredChunks = append(filteredChunks, chunk)
|
||||
continue
|
||||
}
|
||||
|
||||
// Get FAQ metadata and check negative questions
|
||||
meta, err := chunkData.FAQMetadata()
|
||||
if err != nil || meta == nil {
|
||||
// If we can't parse metadata, keep the chunk
|
||||
filteredChunks = append(filteredChunks, chunk)
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if query matches any negative question
|
||||
if s.matchesNegativeQuestions(queryTextLower, meta.NegativeQuestions) {
|
||||
logger.Debugf(ctx, "Filtered FAQ chunk %s due to negative question match", chunk.ChunkID)
|
||||
continue
|
||||
}
|
||||
|
||||
// Keep the chunk
|
||||
filteredChunks = append(filteredChunks, chunk)
|
||||
}
|
||||
|
||||
return filteredChunks
|
||||
}
|
||||
|
||||
// matchesNegativeQuestions checks if the query text matches any negative questions.
|
||||
// Returns true if the query matches any negative question, false otherwise.
|
||||
func (s *knowledgeBaseService) matchesNegativeQuestions(queryTextLower string, negativeQuestions []string) bool {
|
||||
if len(negativeQuestions) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, negativeQ := range negativeQuestions {
|
||||
negativeQLower := strings.ToLower(strings.TrimSpace(negativeQ))
|
||||
if negativeQLower == "" {
|
||||
continue
|
||||
}
|
||||
// Check if query text is exactly the same as the negative question
|
||||
if queryTextLower == negativeQLower {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// classifyRetrievalResults separates retrieval results by retriever type (vector vs keyword).
|
||||
func classifyRetrievalResults(ctx context.Context, retrieveResults []*types.RetrieveResult) (
|
||||
vectorResults, keywordResults []*types.IndexWithScore,
|
||||
) {
|
||||
for _, retrieveResult := range retrieveResults {
|
||||
logger.Infof(ctx, "Retrieval results, engine: %v, retriever: %v, count: %v",
|
||||
retrieveResult.RetrieverEngineType,
|
||||
retrieveResult.RetrieverType,
|
||||
len(retrieveResult.Results),
|
||||
)
|
||||
if retrieveResult.RetrieverType == types.VectorRetrieverType {
|
||||
vectorResults = append(vectorResults, retrieveResult.Results...)
|
||||
} else {
|
||||
keywordResults = append(keywordResults, retrieveResult.Results...)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// fuseOrDeduplicate either fuses vector+keyword results via RRF or deduplicates vector-only results.
|
||||
func fuseOrDeduplicate(ctx context.Context, vectorResults, keywordResults []*types.IndexWithScore) []*types.IndexWithScore {
|
||||
if len(keywordResults) == 0 {
|
||||
// Vector-only: keep original embedding scores (important for FAQ)
|
||||
result := deduplicateByScore(vectorResults)
|
||||
logger.Infof(ctx, "Result count after deduplication: %d", len(result))
|
||||
return result
|
||||
}
|
||||
// Hybrid: use RRF fusion to merge vector + keyword results
|
||||
result := fuseWithRRF(ctx, vectorResults, keywordResults)
|
||||
logger.Infof(ctx, "Result count after RRF fusion: %d", len(result))
|
||||
return result
|
||||
}
|
||||
|
||||
// sortByScoreDesc is a reusable sort comparator for IndexWithScore slices (descending by Score).
|
||||
func sortByScoreDesc(a, b *types.IndexWithScore) int {
|
||||
if a.Score > b.Score {
|
||||
return -1
|
||||
} else if a.Score < b.Score {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// deduplicateByScore deduplicates retrieval results by chunk ID, keeping the highest score
|
||||
// for each chunk. Returns the results sorted by score descending.
|
||||
// Used when only a single retriever (e.g. vector-only for FAQ) is active.
|
||||
func deduplicateByScore(results []*types.IndexWithScore) []*types.IndexWithScore {
|
||||
chunkInfoMap := make(map[string]*types.IndexWithScore, len(results))
|
||||
for _, r := range results {
|
||||
if existing, exists := chunkInfoMap[r.ChunkID]; !exists || r.Score > existing.Score {
|
||||
chunkInfoMap[r.ChunkID] = r
|
||||
}
|
||||
}
|
||||
deduped := make([]*types.IndexWithScore, 0, len(chunkInfoMap))
|
||||
for _, info := range chunkInfoMap {
|
||||
deduped = append(deduped, info)
|
||||
}
|
||||
slices.SortFunc(deduped, sortByScoreDesc)
|
||||
return deduped
|
||||
}
|
||||
|
||||
// fuseWithRRF merges vector and keyword retrieval results using Reciprocal Rank Fusion.
|
||||
// RRF score = vectorWeight/(k+vectorRank) + keywordWeight/(k+keywordRank), with k=60.
|
||||
// The merged results are sorted by RRF score descending.
|
||||
func fuseWithRRF(ctx context.Context, vectorResults, keywordResults []*types.IndexWithScore) []*types.IndexWithScore {
|
||||
const rrfK = 60
|
||||
const vectorWeight = 0.7
|
||||
const keywordWeight = 0.3
|
||||
|
||||
// Build rank maps for each retriever (already sorted by score from retriever)
|
||||
vectorRanks := make(map[string]int, len(vectorResults))
|
||||
for i, r := range vectorResults {
|
||||
if _, exists := vectorRanks[r.ChunkID]; !exists {
|
||||
vectorRanks[r.ChunkID] = i + 1 // 1-indexed rank
|
||||
}
|
||||
}
|
||||
keywordRanks := make(map[string]int, len(keywordResults))
|
||||
for i, r := range keywordResults {
|
||||
if _, exists := keywordRanks[r.ChunkID]; !exists {
|
||||
keywordRanks[r.ChunkID] = i + 1
|
||||
}
|
||||
}
|
||||
|
||||
// Collect all unique chunks — prefer vector result's metadata for each chunk
|
||||
chunkInfoMap := make(map[string]*types.IndexWithScore)
|
||||
for _, r := range vectorResults {
|
||||
if existing, exists := chunkInfoMap[r.ChunkID]; !exists || r.Score > existing.Score {
|
||||
chunkInfoMap[r.ChunkID] = r
|
||||
}
|
||||
}
|
||||
for _, r := range keywordResults {
|
||||
if _, exists := chunkInfoMap[r.ChunkID]; !exists {
|
||||
chunkInfoMap[r.ChunkID] = r
|
||||
}
|
||||
}
|
||||
|
||||
// Compute weighted RRF scores and assign to each chunk
|
||||
result := make([]*types.IndexWithScore, 0, len(chunkInfoMap))
|
||||
for chunkID, info := range chunkInfoMap {
|
||||
rrfScore := 0.0
|
||||
if rank, ok := vectorRanks[chunkID]; ok {
|
||||
rrfScore += vectorWeight / float64(rrfK+rank)
|
||||
}
|
||||
if rank, ok := keywordRanks[chunkID]; ok {
|
||||
rrfScore += keywordWeight / float64(rrfK+rank)
|
||||
}
|
||||
info.Score = rrfScore
|
||||
result = append(result, info)
|
||||
}
|
||||
slices.SortFunc(result, sortByScoreDesc)
|
||||
|
||||
// Log top results for debugging
|
||||
for i, chunk := range result {
|
||||
if i >= 15 {
|
||||
break
|
||||
}
|
||||
vRank, vOk := vectorRanks[chunk.ChunkID]
|
||||
kRank, kOk := keywordRanks[chunk.ChunkID]
|
||||
logger.Debugf(ctx, "RRF rank %d: chunk_id=%s, rrf_score=%.6f, vector_rank=%v(%v), keyword_rank=%v(%v)",
|
||||
i, chunk.ChunkID, chunk.Score, vRank, vOk, kRank, kOk)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// processSearchResults handles the processing of search results, optimizing database queries.
|
||||
func (s *knowledgeBaseService) processSearchResults(ctx context.Context,
|
||||
chunks []*types.IndexWithScore,
|
||||
skipEnrichment bool,
|
||||
) ([]*types.SearchResult, error) {
|
||||
if len(chunks) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
|
||||
// Collect all knowledge and chunk IDs, track scores and match info
|
||||
index := s.buildChunkIndex(chunks)
|
||||
|
||||
// Batch fetch knowledge data (include shared KB so cross-tenant retrieval works)
|
||||
logger.Infof(ctx, "Fetching knowledge data for %d IDs", len(index.knowledgeIDs))
|
||||
knowledgeMap, err := s.fetchKnowledgeDataWithShared(ctx, tenantID, index.knowledgeIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Batch fetch chunks (include shared KB chunks)
|
||||
logger.Infof(ctx, "Fetching chunk data for %d IDs", len(index.chunkIDs))
|
||||
allChunks, err := s.listChunksByIDWithShared(ctx, tenantID, index.chunkIDs)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
"chunk_ids": index.chunkIDs,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "Chunk data fetched successfully, count: %d", len(allChunks))
|
||||
|
||||
// Build chunk map and collect enrichment IDs (parent, related, nearby)
|
||||
chunkMap := make(map[string]*types.Chunk, len(allChunks))
|
||||
for _, chunk := range allChunks {
|
||||
chunkMap[chunk.ID] = chunk
|
||||
}
|
||||
|
||||
if !skipEnrichment {
|
||||
additionalChunkIDs := s.collectEnrichmentChunkIDs(ctx, allChunks, index)
|
||||
if len(additionalChunkIDs) > 0 {
|
||||
logger.Infof(ctx, "Fetching %d additional chunks", len(additionalChunkIDs))
|
||||
additionalChunks, err := s.listChunksByIDWithShared(ctx, tenantID, additionalChunkIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to fetch some additional chunks: %v", err)
|
||||
} else {
|
||||
for _, chunk := range additionalChunks {
|
||||
chunkMap[chunk.ID] = chunk
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build final search results
|
||||
searchResults := s.assembleSearchResults(ctx, chunks, chunkMap, knowledgeMap, index, skipEnrichment)
|
||||
logger.Infof(ctx, "Search results processed, total: %d", len(searchResults))
|
||||
return searchResults, nil
|
||||
}
|
||||
|
||||
// chunkIndex holds pre-computed lookup structures for processing search results.
|
||||
type chunkIndex struct {
|
||||
knowledgeIDs []string
|
||||
chunkIDs []string
|
||||
scores map[string]float64
|
||||
matchTypes map[string]types.MatchType
|
||||
matchedContents map[string]string
|
||||
processedIDs map[string]bool // tracks all IDs (chunk + enrichment) to avoid duplicates
|
||||
}
|
||||
|
||||
// buildChunkIndex collects knowledge/chunk IDs and builds score/matchType maps
|
||||
// from the raw retrieval results.
|
||||
func (s *knowledgeBaseService) buildChunkIndex(chunks []*types.IndexWithScore) *chunkIndex {
|
||||
idx := &chunkIndex{
|
||||
scores: make(map[string]float64, len(chunks)),
|
||||
matchTypes: make(map[string]types.MatchType, len(chunks)),
|
||||
matchedContents: make(map[string]string, len(chunks)),
|
||||
processedIDs: make(map[string]bool, len(chunks)*2),
|
||||
}
|
||||
|
||||
processedKnowledgeIDs := make(map[string]bool)
|
||||
for _, chunk := range chunks {
|
||||
if !processedKnowledgeIDs[chunk.KnowledgeID] {
|
||||
idx.knowledgeIDs = append(idx.knowledgeIDs, chunk.KnowledgeID)
|
||||
processedKnowledgeIDs[chunk.KnowledgeID] = true
|
||||
}
|
||||
idx.chunkIDs = append(idx.chunkIDs, chunk.ChunkID)
|
||||
idx.scores[chunk.ChunkID] = chunk.Score
|
||||
idx.matchTypes[chunk.ChunkID] = chunk.MatchType
|
||||
idx.matchedContents[chunk.ChunkID] = chunk.Content
|
||||
}
|
||||
return idx
|
||||
}
|
||||
|
||||
// collectEnrichmentChunkIDs gathers IDs for parent, related, and nearby chunks
|
||||
// that should be fetched to enrich the search results.
|
||||
func (s *knowledgeBaseService) collectEnrichmentChunkIDs(
|
||||
ctx context.Context,
|
||||
allChunks []*types.Chunk,
|
||||
idx *chunkIndex,
|
||||
) []string {
|
||||
// Mark all primary chunks as processed
|
||||
for _, chunk := range allChunks {
|
||||
idx.processedIDs[chunk.ID] = true
|
||||
}
|
||||
|
||||
var additionalIDs []string
|
||||
|
||||
for _, chunk := range allChunks {
|
||||
// Collect parent chunks
|
||||
if chunk.ParentChunkID != "" && !idx.processedIDs[chunk.ParentChunkID] {
|
||||
additionalIDs = append(additionalIDs, chunk.ParentChunkID)
|
||||
idx.processedIDs[chunk.ParentChunkID] = true
|
||||
idx.scores[chunk.ParentChunkID] = idx.scores[chunk.ID]
|
||||
idx.matchTypes[chunk.ParentChunkID] = types.MatchTypeParentChunk
|
||||
}
|
||||
|
||||
// Collect related chunks
|
||||
relationChunkIDs := s.collectRelatedChunkIDs(chunk, idx.processedIDs)
|
||||
for _, chunkID := range relationChunkIDs {
|
||||
additionalIDs = append(additionalIDs, chunkID)
|
||||
idx.matchTypes[chunkID] = types.MatchTypeRelationChunk
|
||||
}
|
||||
|
||||
// Add nearby chunks (prev and next) for text chunks
|
||||
if slices.Contains([]string{types.ChunkTypeText}, chunk.ChunkType) {
|
||||
if chunk.NextChunkID != "" && !idx.processedIDs[chunk.NextChunkID] {
|
||||
additionalIDs = append(additionalIDs, chunk.NextChunkID)
|
||||
idx.processedIDs[chunk.NextChunkID] = true
|
||||
idx.matchTypes[chunk.NextChunkID] = types.MatchTypeNearByChunk
|
||||
}
|
||||
if chunk.PreChunkID != "" && !idx.processedIDs[chunk.PreChunkID] {
|
||||
additionalIDs = append(additionalIDs, chunk.PreChunkID)
|
||||
idx.processedIDs[chunk.PreChunkID] = true
|
||||
idx.matchTypes[chunk.PreChunkID] = types.MatchTypeNearByChunk
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return additionalIDs
|
||||
}
|
||||
|
||||
// assembleSearchResults builds the final []*types.SearchResult from chunk data and knowledge data.
|
||||
// Primary results (from input chunks) are added first in order, then enrichment results.
|
||||
func (s *knowledgeBaseService) assembleSearchResults(
|
||||
ctx context.Context,
|
||||
inputChunks []*types.IndexWithScore,
|
||||
chunkMap map[string]*types.Chunk,
|
||||
knowledgeMap map[string]*types.Knowledge,
|
||||
idx *chunkIndex,
|
||||
skipEnrichment bool,
|
||||
) []*types.SearchResult {
|
||||
var searchResults []*types.SearchResult
|
||||
addedChunkIDs := make(map[string]bool)
|
||||
const maxInvalidChunkLog = 8
|
||||
invalidChunkCnt := 0
|
||||
invalidChunkSamples := make([]string, 0, maxInvalidChunkLog)
|
||||
|
||||
// First pass: Add results in the original order from input chunks
|
||||
for _, inputChunk := range inputChunks {
|
||||
chunk, exists := chunkMap[inputChunk.ChunkID]
|
||||
if !exists {
|
||||
logger.Debugf(ctx, "Chunk not found in chunkMap: %s", inputChunk.ChunkID)
|
||||
continue
|
||||
}
|
||||
if !s.isValidTextChunk(chunk) {
|
||||
invalidChunkCnt++
|
||||
if len(invalidChunkSamples) < maxInvalidChunkLog {
|
||||
invalidChunkSamples = append(invalidChunkSamples, chunk.ID+":"+chunk.ChunkType)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if addedChunkIDs[chunk.ID] {
|
||||
continue
|
||||
}
|
||||
|
||||
score := idx.scores[chunk.ID]
|
||||
if knowledge, ok := knowledgeMap[chunk.KnowledgeID]; ok {
|
||||
matchType := idx.matchTypes[chunk.ID]
|
||||
matchedContent := idx.matchedContents[chunk.ID]
|
||||
searchResults = append(searchResults, s.buildSearchResult(chunk, knowledge, score, matchType, matchedContent))
|
||||
addedChunkIDs[chunk.ID] = true
|
||||
} else {
|
||||
logger.Warnf(ctx, "Knowledge not found for chunk: %s, knowledge_id: %s", chunk.ID, chunk.KnowledgeID)
|
||||
}
|
||||
}
|
||||
if invalidChunkCnt > 0 {
|
||||
logger.Debugf(ctx,
|
||||
"Skip non-text chunks in search results: total=%d sampled=%d samples=%v",
|
||||
invalidChunkCnt, len(invalidChunkSamples), invalidChunkSamples,
|
||||
)
|
||||
}
|
||||
|
||||
// Second pass: Add enrichment chunks (parent, nearby, relation)
|
||||
if !skipEnrichment {
|
||||
for chunkID, chunk := range chunkMap {
|
||||
if addedChunkIDs[chunkID] || !s.isValidTextChunk(chunk) {
|
||||
continue
|
||||
}
|
||||
|
||||
score, hasScore := idx.scores[chunkID]
|
||||
if !hasScore || score <= 0 {
|
||||
score = 0.0
|
||||
}
|
||||
|
||||
if knowledge, ok := knowledgeMap[chunk.KnowledgeID]; ok {
|
||||
matchType := types.MatchTypeParentChunk
|
||||
if specificType, exists := idx.matchTypes[chunkID]; exists {
|
||||
matchType = specificType
|
||||
} else {
|
||||
logger.Warnf(ctx, "Unkonwn match type for chunk: %s", chunkID)
|
||||
continue
|
||||
}
|
||||
matchedContent := idx.matchedContents[chunkID]
|
||||
searchResults = append(searchResults, s.buildSearchResult(chunk, knowledge, score, matchType, matchedContent))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return searchResults
|
||||
}
|
||||
|
||||
// collectRelatedChunkIDs extracts related chunk IDs from a chunk.
|
||||
func (s *knowledgeBaseService) collectRelatedChunkIDs(chunk *types.Chunk, processedIDs map[string]bool) []string {
|
||||
var relatedIDs []string
|
||||
if len(chunk.RelationChunks) > 0 {
|
||||
var relations []string
|
||||
if err := json.Unmarshal(chunk.RelationChunks, &relations); err == nil {
|
||||
for _, id := range relations {
|
||||
if !processedIDs[id] {
|
||||
relatedIDs = append(relatedIDs, id)
|
||||
processedIDs[id] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return relatedIDs
|
||||
}
|
||||
|
||||
// buildSearchResult creates a search result from chunk and knowledge.
|
||||
func (s *knowledgeBaseService) buildSearchResult(chunk *types.Chunk,
|
||||
knowledge *types.Knowledge,
|
||||
score float64,
|
||||
matchType types.MatchType,
|
||||
matchedContent string,
|
||||
) *types.SearchResult {
|
||||
return &types.SearchResult{
|
||||
ID: chunk.ID,
|
||||
Content: chunk.Content,
|
||||
KnowledgeID: chunk.KnowledgeID,
|
||||
ChunkIndex: chunk.ChunkIndex,
|
||||
KnowledgeTitle: knowledge.Title,
|
||||
StartAt: chunk.StartAt,
|
||||
EndAt: chunk.EndAt,
|
||||
Seq: chunk.ChunkIndex,
|
||||
Score: score,
|
||||
MatchType: matchType,
|
||||
Metadata: knowledge.GetMetadata(),
|
||||
ChunkType: string(chunk.ChunkType),
|
||||
ParentChunkID: chunk.ParentChunkID,
|
||||
ImageInfo: chunk.ImageInfo,
|
||||
KnowledgeFilename: knowledge.FileName,
|
||||
KnowledgeSource: knowledge.Source,
|
||||
ChunkMetadata: chunk.Metadata,
|
||||
MatchedContent: matchedContent,
|
||||
KnowledgeBaseID: knowledge.KnowledgeBaseID,
|
||||
}
|
||||
}
|
||||
|
||||
// isValidTextChunk checks if a chunk is a valid text chunk.
|
||||
func (s *knowledgeBaseService) isValidTextChunk(chunk *types.Chunk) bool {
|
||||
return slices.Contains([]types.ChunkType{
|
||||
types.ChunkTypeText, types.ChunkTypeSummary,
|
||||
types.ChunkTypeTableColumn, types.ChunkTypeTableSummary,
|
||||
types.ChunkTypeFAQ,
|
||||
}, chunk.ChunkType)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// fetchKnowledgeData gets knowledge data in batch.
|
||||
func (s *knowledgeBaseService) fetchKnowledgeData(ctx context.Context,
|
||||
tenantID uint64,
|
||||
knowledgeIDs []string,
|
||||
) (map[string]*types.Knowledge, error) {
|
||||
knowledges, err := s.kgRepo.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
"knowledge_ids": knowledgeIDs,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
knowledgeMap := make(map[string]*types.Knowledge, len(knowledges))
|
||||
for _, knowledge := range knowledges {
|
||||
knowledgeMap[knowledge.ID] = knowledge
|
||||
}
|
||||
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
|
||||
// fetchKnowledgeDataWithShared gets knowledge data in batch, including knowledge
|
||||
// from shared KBs the user has access to.
|
||||
func (s *knowledgeBaseService) fetchKnowledgeDataWithShared(ctx context.Context,
|
||||
tenantID uint64,
|
||||
knowledgeIDs []string,
|
||||
) (map[string]*types.Knowledge, error) {
|
||||
knowledgeMap, err := s.fetchKnowledgeData(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
missingIDs := s.findMissingIDs(knowledgeIDs, func(id string) bool {
|
||||
return knowledgeMap[id] != nil
|
||||
})
|
||||
if len(missingIDs) == 0 {
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
logger.Infof(ctx, "[fetchKnowledgeDataWithShared] %d knowledge IDs not found in current tenant, attempting shared KB lookup", len(missingIDs))
|
||||
|
||||
userID, ok := s.extractUserID(ctx)
|
||||
if !ok {
|
||||
logger.Warnf(ctx, "[fetchKnowledgeDataWithShared] userID not found or empty in context, skipping shared KB lookup")
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[fetchKnowledgeDataWithShared] Looking up %d missing knowledge IDs with userID=%s", len(missingIDs), userID)
|
||||
for _, id := range missingIDs {
|
||||
k, err := s.kgRepo.GetKnowledgeByIDOnly(ctx, id)
|
||||
if err != nil || k == nil || k.KnowledgeBaseID == "" {
|
||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Knowledge %s not found or has no KB", id)
|
||||
continue
|
||||
}
|
||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, k.KnowledgeBaseID, userID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Permission check error for KB %s: %v", k.KnowledgeBaseID, err)
|
||||
continue
|
||||
}
|
||||
if !hasPermission {
|
||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] No permission for KB %s", k.KnowledgeBaseID)
|
||||
continue
|
||||
}
|
||||
logger.Debugf(ctx, "[fetchKnowledgeDataWithShared] Found shared knowledge %s in KB %s", id, k.KnowledgeBaseID)
|
||||
knowledgeMap[k.ID] = k
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[fetchKnowledgeDataWithShared] After shared lookup, total knowledge found: %d", len(knowledgeMap))
|
||||
return knowledgeMap, nil
|
||||
}
|
||||
|
||||
// listChunksByIDWithShared fetches chunks by IDs, including chunks from shared KBs the user has access to.
|
||||
func (s *knowledgeBaseService) listChunksByIDWithShared(ctx context.Context,
|
||||
tenantID uint64,
|
||||
chunkIDs []string,
|
||||
) ([]*types.Chunk, error) {
|
||||
chunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
foundSet := make(map[string]bool, len(chunks))
|
||||
for _, c := range chunks {
|
||||
if c != nil {
|
||||
foundSet[c.ID] = true
|
||||
}
|
||||
}
|
||||
|
||||
missing := s.findMissingIDs(chunkIDs, func(id string) bool {
|
||||
return foundSet[id]
|
||||
})
|
||||
if len(missing) == 0 {
|
||||
return chunks, nil
|
||||
}
|
||||
logger.Infof(ctx, "[listChunksByIDWithShared] %d chunks not found in current tenant, attempting shared KB lookup", len(missing))
|
||||
|
||||
userID, ok := s.extractUserID(ctx)
|
||||
if !ok {
|
||||
logger.Warnf(ctx, "[listChunksByIDWithShared] userID not found or empty in context, skipping shared KB lookup")
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[listChunksByIDWithShared] Looking up %d missing chunks with userID=%s", len(missing), userID)
|
||||
crossChunks, err := s.chunkRepo.ListChunksByIDOnly(ctx, missing)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[listChunksByIDWithShared] Failed to fetch chunks by ID only: %v", err)
|
||||
return chunks, nil
|
||||
}
|
||||
logger.Infof(ctx, "[listChunksByIDWithShared] Found %d chunks without tenant filter", len(crossChunks))
|
||||
|
||||
for _, c := range crossChunks {
|
||||
if c == nil || c.KnowledgeBaseID == "" {
|
||||
continue
|
||||
}
|
||||
hasPermission, err := s.kbShareService.HasKBPermission(ctx, c.KnowledgeBaseID, userID, types.OrgRoleViewer)
|
||||
if err != nil {
|
||||
logger.Debugf(ctx, "[listChunksByIDWithShared] Permission check error for KB %s: %v", c.KnowledgeBaseID, err)
|
||||
continue
|
||||
}
|
||||
if !hasPermission {
|
||||
logger.Debugf(ctx, "[listChunksByIDWithShared] No permission for KB %s", c.KnowledgeBaseID)
|
||||
continue
|
||||
}
|
||||
chunks = append(chunks, c)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[listChunksByIDWithShared] After shared lookup, total chunks: %d", len(chunks))
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
// findMissingIDs returns IDs from the input slice that are not found by the exists predicate.
|
||||
func (s *knowledgeBaseService) findMissingIDs(ids []string, exists func(string) bool) []string {
|
||||
var missing []string
|
||||
for _, id := range ids {
|
||||
if !exists(id) {
|
||||
missing = append(missing, id)
|
||||
}
|
||||
}
|
||||
return missing
|
||||
}
|
||||
|
||||
// extractUserID extracts the user ID from context, returning ("", false) if not found.
|
||||
func (s *knowledgeBaseService) extractUserID(ctx context.Context) (string, bool) {
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal == nil {
|
||||
return "", false
|
||||
}
|
||||
userID, ok := userIDVal.(string)
|
||||
if !ok || userID == "" {
|
||||
return "", false
|
||||
}
|
||||
return userID, true
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,368 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
llmcontext "github.com/Tencent/WeKnora/internal/application/service/llmcontext"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/models/rerank"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// AgentQA performs agent-based question answering with conversation history and streaming support
|
||||
// customAgent is optional - if provided, uses custom agent configuration instead of tenant defaults
|
||||
// summaryModelID is optional - if provided, overrides the model from customAgent config
|
||||
func (s *sessionService) AgentQA(
|
||||
ctx context.Context,
|
||||
req *types.QARequest,
|
||||
eventBus *event.EventBus,
|
||||
) error {
|
||||
sessionID := req.Session.ID
|
||||
sessionJSON, err := json.Marshal(req.Session)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to marshal session, session ID: %s, error: %v", sessionID, err)
|
||||
return fmt.Errorf("failed to marshal session: %w", err)
|
||||
}
|
||||
|
||||
// customAgent is required for AgentQA (handler has already done permission check for shared agent)
|
||||
if req.CustomAgent == nil {
|
||||
logger.Warnf(ctx, "Custom agent not provided for session: %s", sessionID)
|
||||
return errors.New("custom agent configuration is required for agent QA")
|
||||
}
|
||||
|
||||
// Resolve retrieval tenant using shared helper
|
||||
agentTenantID := s.resolveRetrievalTenantID(ctx, req)
|
||||
logger.Infof(ctx, "Start agent-based question answering, session ID: %s, agent tenant ID: %d, query: %s, session: %s",
|
||||
sessionID, agentTenantID, req.Query, string(sessionJSON))
|
||||
|
||||
var tenantInfo *types.Tenant
|
||||
if v := ctx.Value(types.TenantInfoContextKey); v != nil {
|
||||
tenantInfo, _ = v.(*types.Tenant)
|
||||
}
|
||||
// When agent belongs to another tenant (shared agent), use agent's tenant for KB/model scope; load tenantInfo if needed
|
||||
if tenantInfo == nil || tenantInfo.ID != agentTenantID {
|
||||
if s.tenantService != nil {
|
||||
if agentTenant, err := s.tenantService.GetTenantByID(ctx, agentTenantID); err == nil && agentTenant != nil {
|
||||
tenantInfo = agentTenant
|
||||
logger.Infof(ctx, "Using agent tenant info for retrieval scope, tenant ID: %d", agentTenantID)
|
||||
}
|
||||
}
|
||||
}
|
||||
if tenantInfo == nil {
|
||||
logger.Warnf(ctx, "Tenant info not available for agent tenant %d, proceeding with defaults", agentTenantID)
|
||||
tenantInfo = &types.Tenant{ID: agentTenantID}
|
||||
}
|
||||
|
||||
// Ensure defaults are set
|
||||
req.CustomAgent.EnsureDefaults()
|
||||
|
||||
// Build AgentConfig from custom agent and tenant info
|
||||
agentConfig, err := s.buildAgentConfig(ctx, req, tenantInfo, agentTenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Resolve model ID using shared helper (AgentQA requires a model, so error if not found)
|
||||
effectiveModelID, err := s.resolveChatModelID(ctx, req, agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if effectiveModelID == "" {
|
||||
logger.Warnf(ctx, "No summary model configured for custom agent %s", req.CustomAgent.ID)
|
||||
return errors.New("summary model (model_id) is not configured in custom agent settings")
|
||||
}
|
||||
|
||||
summaryModel, err := s.modelService.GetChatModel(ctx, effectiveModelID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get chat model: %v", err)
|
||||
return fmt.Errorf("failed to get chat model: %w", err)
|
||||
}
|
||||
|
||||
// Get rerank model from custom agent config (only required when knowledge bases are configured)
|
||||
var rerankModel rerank.Reranker
|
||||
hasKnowledge := len(agentConfig.KnowledgeBases) > 0 || len(agentConfig.KnowledgeIDs) > 0
|
||||
if hasKnowledge {
|
||||
rerankModelID := req.CustomAgent.Config.RerankModelID
|
||||
if rerankModelID == "" {
|
||||
logger.Warnf(ctx, "No rerank model configured for custom agent %s, but knowledge bases are specified", req.CustomAgent.ID)
|
||||
return errors.New("rerank model (rerank_model_id) is not configured in custom agent settings")
|
||||
}
|
||||
|
||||
rerankModel, err = s.modelService.GetRerankModel(ctx, rerankModelID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get rerank model: %v", err)
|
||||
return fmt.Errorf("failed to get rerank model: %w", err)
|
||||
}
|
||||
} else {
|
||||
logger.Infof(ctx, "No knowledge bases configured, skipping rerank model initialization")
|
||||
}
|
||||
|
||||
// Get or create contextManager for this session
|
||||
contextManager := s.getContextManagerForSession(ctx, req.Session, summaryModel)
|
||||
|
||||
// Set system prompt for the current agent in context manager
|
||||
// This ensures the context uses the correct system prompt when switching agents
|
||||
systemPrompt := agentConfig.ResolveSystemPrompt(agentConfig.WebSearchEnabled)
|
||||
if systemPrompt != "" {
|
||||
if err := contextManager.SetSystemPrompt(ctx, sessionID, systemPrompt); err != nil {
|
||||
logger.Warnf(ctx, "Failed to set system prompt in context manager: %v", err)
|
||||
} else {
|
||||
logger.Infof(ctx, "System prompt updated in context manager for agent")
|
||||
}
|
||||
}
|
||||
|
||||
// Get LLM context from context manager
|
||||
llmContext, err := s.getContextForSession(ctx, contextManager, sessionID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get LLM context: %v, continuing without history", err)
|
||||
llmContext = []chat.Message{}
|
||||
}
|
||||
logger.Infof(ctx, "Loaded %d messages from LLM context manager", len(llmContext))
|
||||
|
||||
// Apply multi-turn configuration for Agent mode
|
||||
// Note: In Agent mode, context is managed by contextManager with compression strategies,
|
||||
// so we don't apply HistoryTurns limit here. HistoryTurns is used in normal (KnowledgeQA) mode.
|
||||
if !agentConfig.MultiTurnEnabled {
|
||||
// Multi-turn disabled, clear history
|
||||
logger.Infof(ctx, "Multi-turn disabled for this agent, clearing history context")
|
||||
llmContext = []chat.Message{}
|
||||
}
|
||||
|
||||
// Create agent engine with EventBus and ContextManager
|
||||
logger.Info(ctx, "Creating agent engine")
|
||||
engine, err := s.agentService.CreateAgentEngine(
|
||||
ctx,
|
||||
agentConfig,
|
||||
summaryModel,
|
||||
rerankModel,
|
||||
eventBus,
|
||||
contextManager,
|
||||
sessionID,
|
||||
)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create agent engine: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Route image data based on agent model's vision capability
|
||||
var agentModelSupportsVision bool
|
||||
if effectiveModelID != "" {
|
||||
if modelInfo, err := s.modelService.GetModelByID(ctx, effectiveModelID); err == nil && modelInfo != nil {
|
||||
agentModelSupportsVision = modelInfo.Parameters.SupportsVision
|
||||
}
|
||||
}
|
||||
|
||||
agentQuery := req.Query
|
||||
var agentImageURLs []string
|
||||
if agentModelSupportsVision && len(req.ImageURLs) > 0 {
|
||||
agentImageURLs = req.ImageURLs
|
||||
logger.Infof(ctx, "Agent model supports vision, passing %d image(s) directly", len(agentImageURLs))
|
||||
} else if req.ImageDescription != "" {
|
||||
agentQuery = req.Query + "\n\n[用户上传图片内容]\n" + req.ImageDescription
|
||||
logger.Infof(ctx, "Agent model does not support vision, appending image description (%d chars)", len(req.ImageDescription))
|
||||
}
|
||||
|
||||
// Execute agent with streaming (asynchronously)
|
||||
// Events will be emitted to EventBus and handled by the Handler layer
|
||||
logger.Info(ctx, "Executing agent with streaming")
|
||||
if _, err := engine.Execute(ctx, sessionID, req.AssistantMessageID, agentQuery, llmContext, agentImageURLs); err != nil {
|
||||
logger.Errorf(ctx, "Agent execution failed: %v", err)
|
||||
// Emit error event to the EventBus used by this agent
|
||||
eventBus.Emit(ctx, event.Event{
|
||||
Type: event.EventError,
|
||||
SessionID: sessionID,
|
||||
Data: event.ErrorData{
|
||||
Error: err.Error(),
|
||||
Stage: "agent_execution",
|
||||
SessionID: sessionID,
|
||||
},
|
||||
})
|
||||
}
|
||||
// Return empty - events will be handled by Handler via EventBus subscription
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildAgentConfig creates a runtime AgentConfig from the QARequest's custom agent configuration,
|
||||
// tenant info, and resolved knowledge bases / search targets.
|
||||
func (s *sessionService) buildAgentConfig(
|
||||
ctx context.Context,
|
||||
req *types.QARequest,
|
||||
tenantInfo *types.Tenant,
|
||||
agentTenantID uint64,
|
||||
) (*types.AgentConfig, error) {
|
||||
customAgent := req.CustomAgent
|
||||
agentConfig := &types.AgentConfig{
|
||||
MaxIterations: customAgent.Config.MaxIterations,
|
||||
ReflectionEnabled: customAgent.Config.ReflectionEnabled,
|
||||
Temperature: customAgent.Config.Temperature,
|
||||
WebSearchEnabled: customAgent.Config.WebSearchEnabled && req.WebSearchEnabled,
|
||||
WebSearchMaxResults: customAgent.Config.WebSearchMaxResults,
|
||||
MultiTurnEnabled: customAgent.Config.MultiTurnEnabled,
|
||||
HistoryTurns: customAgent.Config.HistoryTurns,
|
||||
MCPSelectionMode: customAgent.Config.MCPSelectionMode,
|
||||
MCPServices: customAgent.Config.MCPServices,
|
||||
Thinking: customAgent.Config.Thinking,
|
||||
RetrieveKBOnlyWhenMentioned: customAgent.Config.RetrieveKBOnlyWhenMentioned,
|
||||
}
|
||||
|
||||
// Configure skills based on CustomAgentConfig
|
||||
s.configureSkillsFromAgent(ctx, agentConfig, customAgent)
|
||||
|
||||
// Resolve knowledge bases using shared helper
|
||||
agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs = s.resolveKnowledgeBases(ctx, req)
|
||||
|
||||
// Use custom agent's allowed tools if specified, otherwise use defaults
|
||||
if len(customAgent.Config.AllowedTools) > 0 {
|
||||
agentConfig.AllowedTools = customAgent.Config.AllowedTools
|
||||
} else {
|
||||
agentConfig.AllowedTools = tools.DefaultAllowedTools()
|
||||
}
|
||||
|
||||
// Use custom agent's system prompt if specified
|
||||
if customAgent.Config.SystemPrompt != "" {
|
||||
agentConfig.UseCustomSystemPrompt = true
|
||||
agentConfig.SystemPrompt = customAgent.Config.SystemPrompt
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent config applied: MaxIterations=%d, Temperature=%.2f, AllowedTools=%v, WebSearchEnabled=%v",
|
||||
agentConfig.MaxIterations, agentConfig.Temperature, agentConfig.AllowedTools, agentConfig.WebSearchEnabled)
|
||||
|
||||
// Set web search max results from tenant config if not set (default: 5)
|
||||
if agentConfig.WebSearchMaxResults == 0 {
|
||||
agentConfig.WebSearchMaxResults = 5
|
||||
if tenantInfo.WebSearchConfig != nil && tenantInfo.WebSearchConfig.MaxResults > 0 {
|
||||
agentConfig.WebSearchMaxResults = tenantInfo.WebSearchConfig.MaxResults
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Merged agent config from tenant %d and session %s", tenantInfo.ID, req.Session.ID)
|
||||
|
||||
// Log knowledge bases if present
|
||||
if len(agentConfig.KnowledgeBases) > 0 {
|
||||
logger.Infof(ctx, "Agent configured with %d knowledge base(s): %v",
|
||||
len(agentConfig.KnowledgeBases), agentConfig.KnowledgeBases)
|
||||
} else {
|
||||
logger.Infof(ctx, "No knowledge bases specified for agent, running in pure agent mode")
|
||||
}
|
||||
|
||||
// Build search targets using agent's tenant (handler has validated access for shared agent)
|
||||
searchTargets, err := s.buildSearchTargets(ctx, agentTenantID, agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to build search targets for agent: %v", err)
|
||||
}
|
||||
agentConfig.SearchTargets = searchTargets
|
||||
logger.Infof(ctx, "Agent search targets built: %d targets", len(searchTargets))
|
||||
|
||||
return agentConfig, nil
|
||||
}
|
||||
|
||||
// configureSkillsFromAgent configures skills settings in AgentConfig based on CustomAgentConfig
|
||||
// Returns the skill directories and allowed skills based on the selection mode:
|
||||
// - "all": uses all preloaded skills
|
||||
// - "selected": uses the explicitly selected skills
|
||||
// - "none" or "": skills are disabled
|
||||
func (s *sessionService) configureSkillsFromAgent(
|
||||
ctx context.Context,
|
||||
agentConfig *types.AgentConfig,
|
||||
customAgent *types.CustomAgent,
|
||||
) {
|
||||
if customAgent == nil {
|
||||
return
|
||||
}
|
||||
// When sandbox is disabled, skills cannot be enabled (no script execution environment)
|
||||
sandboxMode := os.Getenv("WEKNORA_SANDBOX_MODE")
|
||||
if sandboxMode == "" || sandboxMode == "disabled" {
|
||||
agentConfig.SkillsEnabled = false
|
||||
agentConfig.SkillDirs = nil
|
||||
agentConfig.AllowedSkills = nil
|
||||
logger.Infof(ctx, "Sandbox is disabled: skills are not available")
|
||||
return
|
||||
}
|
||||
|
||||
switch customAgent.Config.SkillsSelectionMode {
|
||||
case "all":
|
||||
// Enable all preloaded skills
|
||||
agentConfig.SkillsEnabled = true
|
||||
agentConfig.SkillDirs = []string{DefaultPreloadedSkillsDir}
|
||||
agentConfig.AllowedSkills = nil // Empty means all skills allowed
|
||||
logger.Infof(ctx, "SkillsSelectionMode=all: enabled all preloaded skills")
|
||||
case "selected":
|
||||
// Enable only selected skills
|
||||
if len(customAgent.Config.SelectedSkills) > 0 {
|
||||
agentConfig.SkillsEnabled = true
|
||||
agentConfig.SkillDirs = []string{DefaultPreloadedSkillsDir}
|
||||
agentConfig.AllowedSkills = customAgent.Config.SelectedSkills
|
||||
logger.Infof(ctx, "SkillsSelectionMode=selected: enabled %d selected skills: %v",
|
||||
len(customAgent.Config.SelectedSkills), customAgent.Config.SelectedSkills)
|
||||
} else {
|
||||
agentConfig.SkillsEnabled = false
|
||||
logger.Infof(ctx, "SkillsSelectionMode=selected but no skills selected: skills disabled")
|
||||
}
|
||||
case "none", "":
|
||||
// Skills disabled
|
||||
agentConfig.SkillsEnabled = false
|
||||
logger.Infof(ctx, "SkillsSelectionMode=%s: skills disabled", customAgent.Config.SkillsSelectionMode)
|
||||
default:
|
||||
// Unknown mode, disable skills
|
||||
agentConfig.SkillsEnabled = false
|
||||
logger.Warnf(ctx, "Unknown SkillsSelectionMode=%s: skills disabled", customAgent.Config.SkillsSelectionMode)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// getContextManagerForSession creates a context manager for the session based on configuration
|
||||
// Returns the configured context manager (tenant-level or session-level) or default
|
||||
func (s *sessionService) getContextManagerForSession(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
chatModel chat.Chat,
|
||||
) interfaces.ContextManager {
|
||||
// Get tenant to access global context configuration
|
||||
tenant, _ := types.TenantInfoFromContext(ctx)
|
||||
// Determine which context config to use: tenant-level or default
|
||||
var contextConfig *types.ContextConfig
|
||||
if tenant != nil && tenant.ContextConfig != nil {
|
||||
// Use tenant-level configuration
|
||||
contextConfig = tenant.ContextConfig
|
||||
logger.Infof(ctx, "Using tenant-level context config for session %s", session.ID)
|
||||
} else {
|
||||
// Use service's default context manager
|
||||
logger.Debugf(ctx, "Using default context manager for session %s", session.ID)
|
||||
contextConfig = &types.ContextConfig{
|
||||
MaxTokens: llmcontext.DefaultMaxTokens,
|
||||
CompressionStrategy: llmcontext.DefaultCompressionStrategy,
|
||||
RecentMessageCount: llmcontext.DefaultRecentMessageCount,
|
||||
SummarizeThreshold: llmcontext.DefaultSummarizeThreshold,
|
||||
}
|
||||
}
|
||||
return llmcontext.NewContextManagerFromConfig(contextConfig, s.sessionStorage, chatModel)
|
||||
}
|
||||
|
||||
// getContextForSession retrieves LLM context for a session
|
||||
func (s *sessionService) getContextForSession(
|
||||
ctx context.Context,
|
||||
contextManager interfaces.ContextManager,
|
||||
sessionID string,
|
||||
) ([]chat.Message, error) {
|
||||
history, err := contextManager.GetContext(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get context: %w", err)
|
||||
}
|
||||
|
||||
// Log context statistics
|
||||
stats, _ := contextManager.GetContextStats(ctx, sessionID)
|
||||
if stats != nil {
|
||||
logger.Infof(ctx, "LLM context stats for session %s: messages=%d, tokens=~%d, compressed=%v",
|
||||
sessionID, stats.MessageCount, stats.TokenCount, stats.IsCompressed)
|
||||
}
|
||||
|
||||
return history, nil
|
||||
}
|
||||
@@ -0,0 +1,806 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
chatpipline "github.com/Tencent/WeKnora/internal/application/service/chat_pipline"
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/tracing"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
)
|
||||
|
||||
// KnowledgeQA performs knowledge base question answering with LLM summarization
|
||||
// Events are emitted through eventBus (references, answer chunks, completion)
|
||||
// customAgent is optional - if provided, uses custom agent configuration for multiTurnEnabled and historyTurns
|
||||
func (s *sessionService) KnowledgeQA(
|
||||
ctx context.Context,
|
||||
req *types.QARequest,
|
||||
eventBus *event.EventBus,
|
||||
) error {
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Knowledge base question answering parameters, session ID: %s, query: %s, webSearchEnabled: %v, enableMemory: %v",
|
||||
req.Session.ID,
|
||||
req.Query,
|
||||
req.WebSearchEnabled,
|
||||
req.EnableMemory,
|
||||
)
|
||||
|
||||
// Resolve knowledge bases using shared helper
|
||||
knowledgeBaseIDs, knowledgeIDs := s.resolveKnowledgeBases(ctx, req)
|
||||
|
||||
// Resolve chat model ID using shared helper
|
||||
chatModelID, err := s.resolveChatModelID(ctx, req, knowledgeBaseIDs, knowledgeIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Initialize ChatManage defaults from config.yaml
|
||||
summaryConfig := types.SummaryConfig{
|
||||
Prompt: s.cfg.Conversation.Summary.Prompt,
|
||||
ContextTemplate: s.cfg.Conversation.Summary.ContextTemplate,
|
||||
Temperature: s.cfg.Conversation.Summary.Temperature,
|
||||
NoMatchPrefix: s.cfg.Conversation.Summary.NoMatchPrefix,
|
||||
MaxCompletionTokens: s.cfg.Conversation.Summary.MaxCompletionTokens,
|
||||
Thinking: s.cfg.Conversation.Summary.Thinking,
|
||||
}
|
||||
fallbackStrategy := types.FallbackStrategy(s.cfg.Conversation.FallbackStrategy)
|
||||
if fallbackStrategy == "" {
|
||||
fallbackStrategy = types.FallbackStrategyFixed
|
||||
logger.Infof(ctx, "Fallback strategy not set, using default: %v", fallbackStrategy)
|
||||
}
|
||||
|
||||
// Resolve chat model vision capability and VLM model ID for image routing
|
||||
var chatModelSupportsVision bool
|
||||
var vlmModelID string
|
||||
if chatModelID != "" {
|
||||
if chatModelInfo, err := s.modelService.GetModelByID(ctx, chatModelID); err == nil && chatModelInfo != nil {
|
||||
chatModelSupportsVision = chatModelInfo.Parameters.SupportsVision
|
||||
}
|
||||
}
|
||||
if req.CustomAgent != nil {
|
||||
vlmModelID = req.CustomAgent.Config.VLMModelID
|
||||
}
|
||||
|
||||
// Resolve retrieval tenant scope using shared helper
|
||||
retrievalTenantID := s.resolveRetrievalTenantID(ctx, req)
|
||||
|
||||
// Build unified search targets (computed once, used throughout pipeline)
|
||||
searchTargets, err := s.buildSearchTargets(ctx, retrievalTenantID, knowledgeBaseIDs, knowledgeIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to build search targets: %v", err)
|
||||
}
|
||||
|
||||
// Create chat management object with session settings
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Creating chat manage object, knowledge base IDs: %v, knowledge IDs: %v, chat model ID: %s, search targets: %d",
|
||||
knowledgeBaseIDs,
|
||||
knowledgeIDs,
|
||||
chatModelID,
|
||||
len(searchTargets),
|
||||
)
|
||||
|
||||
// Get UserID from context
|
||||
userID, _ := types.UserIDFromContext(ctx)
|
||||
|
||||
chatManage := &types.ChatManage{
|
||||
Query: req.Query,
|
||||
RewriteQuery: req.Query,
|
||||
SessionID: req.Session.ID,
|
||||
UserID: userID,
|
||||
MessageID: req.AssistantMessageID,
|
||||
KnowledgeBaseIDs: knowledgeBaseIDs,
|
||||
KnowledgeIDs: knowledgeIDs,
|
||||
SearchTargets: searchTargets,
|
||||
VectorThreshold: s.cfg.Conversation.VectorThreshold,
|
||||
KeywordThreshold: s.cfg.Conversation.KeywordThreshold,
|
||||
EmbeddingTopK: s.cfg.Conversation.EmbeddingTopK,
|
||||
RerankTopK: s.cfg.Conversation.RerankTopK,
|
||||
RerankThreshold: s.cfg.Conversation.RerankThreshold,
|
||||
MaxRounds: s.cfg.Conversation.MaxRounds,
|
||||
ChatModelID: chatModelID,
|
||||
SummaryConfig: summaryConfig,
|
||||
FallbackStrategy: fallbackStrategy,
|
||||
FallbackResponse: s.cfg.Conversation.FallbackResponse,
|
||||
FallbackPrompt: s.cfg.Conversation.FallbackPrompt,
|
||||
EventBus: eventBus.AsEventBusInterface(),
|
||||
WebSearchEnabled: req.WebSearchEnabled,
|
||||
EnableMemory: req.EnableMemory,
|
||||
TenantID: retrievalTenantID,
|
||||
RewritePromptSystem: s.cfg.Conversation.RewritePromptSystem,
|
||||
RewritePromptUser: s.cfg.Conversation.RewritePromptUser,
|
||||
EnableRewrite: s.cfg.Conversation.EnableRewrite,
|
||||
EnableQueryExpansion: s.cfg.Conversation.EnableQueryExpansion,
|
||||
// Image support
|
||||
UserMessageID: req.UserMessageID,
|
||||
Images: req.ImageURLs,
|
||||
ImageDescription: req.ImageDescription,
|
||||
VLMModelID: vlmModelID,
|
||||
ChatModelSupportsVision: chatModelSupportsVision,
|
||||
}
|
||||
|
||||
// Apply custom agent overrides (system prompt, temperature, retrieval params,
|
||||
// rewrite, fallback, FAQ strategy, history turns)
|
||||
s.applyAgentOverridesToChatManage(ctx, req.CustomAgent, chatManage)
|
||||
|
||||
// Determine pipeline based on knowledge bases availability and web search setting
|
||||
// If no knowledge bases are selected AND web search is disabled, use pure chat pipeline
|
||||
// Otherwise use rag_stream pipeline (which handles both KB search and web search)
|
||||
var pipeline []types.EventType
|
||||
if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 && !req.WebSearchEnabled {
|
||||
logger.Info(ctx, "No knowledge bases selected and web search disabled, using chat pipeline")
|
||||
// For pure chat, UserContent is the Query (since INTO_CHAT_MESSAGE is skipped)
|
||||
// Only append image text description for non-vision models; vision models see images directly
|
||||
userContent := req.Query
|
||||
if req.ImageDescription != "" && !chatModelSupportsVision {
|
||||
userContent += "\n\n[用户上传图片内容]\n" + req.ImageDescription
|
||||
}
|
||||
chatManage.UserContent = userContent
|
||||
|
||||
// Use chat_history_stream if multi-turn is enabled, otherwise use chat_stream
|
||||
if chatManage.MaxRounds > 0 {
|
||||
logger.Infof(ctx, "Multi-turn enabled with maxRounds=%d, using chat_history_stream pipeline", chatManage.MaxRounds)
|
||||
pipeline = types.Pipline["chat_history_stream"]
|
||||
} else {
|
||||
logger.Info(ctx, "Multi-turn disabled, using chat_stream pipeline")
|
||||
pipeline = types.Pipline["chat_stream"]
|
||||
}
|
||||
} else {
|
||||
if req.WebSearchEnabled && len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 {
|
||||
logger.Info(ctx, "Web search enabled without knowledge bases, using rag_stream pipeline for web search only")
|
||||
} else {
|
||||
logger.Info(ctx, "Knowledge bases selected, using rag_stream pipeline")
|
||||
}
|
||||
pipeline = types.Pipline["rag_stream"]
|
||||
}
|
||||
|
||||
// Start knowledge QA event processing (set session tenant so pipeline session/message lookups use session owner)
|
||||
ctx = context.WithValue(ctx, types.SessionTenantIDContextKey, req.Session.TenantID)
|
||||
logger.Info(ctx, "Triggering question answering event")
|
||||
err = s.KnowledgeQAByEvent(ctx, chatManage, pipeline)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"session_id": req.Session.ID,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// Emit references event if we have search results
|
||||
if len(chatManage.MergeResult) > 0 {
|
||||
logger.Infof(ctx, "Emitting references event with %d results", len(chatManage.MergeResult))
|
||||
if err := eventBus.Emit(ctx, event.Event{
|
||||
ID: generateEventID("references"),
|
||||
Type: event.EventAgentReferences,
|
||||
SessionID: req.Session.ID,
|
||||
Data: event.AgentReferencesData{
|
||||
References: chatManage.MergeResult,
|
||||
},
|
||||
}); err != nil {
|
||||
logger.Errorf(ctx, "Failed to emit references event: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Note: Answer events are now emitted directly by chat_completion_stream plugin
|
||||
// Completion event will be emitted when the last answer event has Done=true
|
||||
// We can optionally add a completion watcher here if needed, but for now
|
||||
// the frontend can detect completion from the Done flag
|
||||
|
||||
logger.Info(ctx, "Knowledge base question answering initiated")
|
||||
return nil
|
||||
}
|
||||
|
||||
// selectChatModelID selects the appropriate chat model ID with priority for Remote models
|
||||
// Priority order:
|
||||
// 1. Session's SummaryModelID if it's a Remote model
|
||||
// 2. First knowledge base with a Remote model (from knowledgeBaseIDs or derived from knowledgeIDs)
|
||||
// 3. Session's SummaryModelID (if not Remote)
|
||||
// 4. First knowledge base's SummaryModelID
|
||||
func (s *sessionService) selectChatModelID(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
knowledgeBaseIDs []string,
|
||||
knowledgeIDs []string,
|
||||
) (string, error) {
|
||||
// If no knowledge base IDs but have knowledge IDs, derive KB IDs from knowledge IDs (include shared KB files)
|
||||
if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) > 0 {
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
knowledgeList, err := s.knowledgeService.GetKnowledgeBatchWithSharedAccess(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get knowledge batch for model selection: %v", err)
|
||||
} else {
|
||||
// Collect unique KB IDs from knowledge items
|
||||
kbIDSet := make(map[string]bool)
|
||||
for _, k := range knowledgeList {
|
||||
if k != nil && k.KnowledgeBaseID != "" {
|
||||
kbIDSet[k.KnowledgeBaseID] = true
|
||||
}
|
||||
}
|
||||
for kbID := range kbIDSet {
|
||||
knowledgeBaseIDs = append(knowledgeBaseIDs, kbID)
|
||||
}
|
||||
logger.Infof(ctx, "Derived %d knowledge base IDs from %d knowledge IDs for model selection",
|
||||
len(knowledgeBaseIDs), len(knowledgeIDs))
|
||||
}
|
||||
}
|
||||
// Check knowledge bases for models
|
||||
if len(knowledgeBaseIDs) > 0 {
|
||||
// Try to find a knowledge base with Remote model
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get knowledge base: %v", err)
|
||||
continue
|
||||
}
|
||||
if kb != nil && kb.SummaryModelID != "" {
|
||||
model, err := s.modelService.GetModelByID(ctx, kb.SummaryModelID)
|
||||
if err == nil && model != nil && model.Source == types.ModelSourceRemote {
|
||||
logger.Info(ctx, "Using Remote summary model from knowledge base")
|
||||
return kb.SummaryModelID, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If no Remote model found, use first knowledge base's model
|
||||
kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, knowledgeBaseIDs[0])
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get knowledge base for model ID: %v", err)
|
||||
return "", fmt.Errorf("failed to get knowledge base %s: %w", knowledgeBaseIDs[0], err)
|
||||
}
|
||||
if kb != nil && kb.SummaryModelID != "" {
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Using summary model from first knowledge base %s: %s",
|
||||
knowledgeBaseIDs[0],
|
||||
kb.SummaryModelID,
|
||||
)
|
||||
return kb.SummaryModelID, nil
|
||||
}
|
||||
}
|
||||
|
||||
// No knowledge bases - try to find any available chat model
|
||||
models, err := s.modelService.ListModels(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to list models: %v", err)
|
||||
return "", fmt.Errorf("failed to list models: %w", err)
|
||||
}
|
||||
for _, model := range models {
|
||||
if model != nil && model.Type == types.ModelTypeKnowledgeQA {
|
||||
logger.Infof(ctx, "Using first available KnowledgeQA model: %s", model.ID)
|
||||
return model.ID, nil
|
||||
}
|
||||
}
|
||||
|
||||
logger.Error(ctx, "No chat model ID available")
|
||||
return "", fmt.Errorf("no chat model ID available: no knowledge bases configured and no available models")
|
||||
}
|
||||
|
||||
// resolveKnowledgeBasesFromAgent resolves knowledge base IDs based on agent's KBSelectionMode.
|
||||
// sessionTenantID is the tenant of the current session (caller); it is compared with
|
||||
// customAgent.TenantID to detect the shared-agent scenario and avoid leaking the
|
||||
// current user's personal shared KBs into the agent's retrieval scope.
|
||||
//
|
||||
// Returns the resolved knowledge base IDs based on the selection mode:
|
||||
// - "all": fetches all knowledge bases for the tenant
|
||||
// - "selected": uses the explicitly configured knowledge bases
|
||||
// - "none": returns empty slice
|
||||
// - default: falls back to configured knowledge bases for backward compatibility
|
||||
func (s *sessionService) resolveKnowledgeBasesFromAgent(
|
||||
ctx context.Context,
|
||||
customAgent *types.CustomAgent,
|
||||
sessionTenantID uint64,
|
||||
) []string {
|
||||
if customAgent == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch customAgent.Config.KBSelectionMode {
|
||||
case "all":
|
||||
// Get own knowledge bases (uses ctx TenantID = agent's tenant)
|
||||
allKBs, err := s.knowledgeBaseService.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list all knowledge bases: %v", err)
|
||||
}
|
||||
kbIDSet := make(map[string]bool)
|
||||
kbIDs := make([]string, 0, len(allKBs))
|
||||
for _, kb := range allKBs {
|
||||
kbIDs = append(kbIDs, kb.ID)
|
||||
kbIDSet[kb.ID] = true
|
||||
}
|
||||
|
||||
// For shared agents (session tenant != agent tenant), only use the agent
|
||||
// tenant's own KBs. Including the current user's shared KBs would leak
|
||||
// unrelated KBs from other organisations into the agent's retrieval scope.
|
||||
isSharedAgent := sessionTenantID != 0 && sessionTenantID != customAgent.TenantID
|
||||
if !isSharedAgent {
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
userIDVal := ctx.Value(types.UserIDContextKey)
|
||||
if userIDVal != nil {
|
||||
if userID, ok := userIDVal.(string); ok && userID != "" && s.kbShareService != nil {
|
||||
sharedList, err := s.kbShareService.ListSharedKnowledgeBases(ctx, userID, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list shared knowledge bases: %v", err)
|
||||
} else {
|
||||
for _, info := range sharedList {
|
||||
if info != nil && info.KnowledgeBase != nil && !kbIDSet[info.KnowledgeBase.ID] {
|
||||
kbIDs = append(kbIDs, info.KnowledgeBase.ID)
|
||||
kbIDSet[info.KnowledgeBase.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.Infof(ctx, "Shared agent detected (session tenant %d != agent tenant %d): skipping user's shared KBs",
|
||||
sessionTenantID, customAgent.TenantID)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "KBSelectionMode=all: loaded %d knowledge bases (own + shared)", len(kbIDs))
|
||||
return kbIDs
|
||||
case "selected":
|
||||
logger.Infof(ctx, "KBSelectionMode=selected: using %d configured knowledge bases", len(customAgent.Config.KnowledgeBases))
|
||||
return customAgent.Config.KnowledgeBases
|
||||
case "none":
|
||||
logger.Infof(ctx, "KBSelectionMode=none: no knowledge bases configured")
|
||||
return nil
|
||||
default:
|
||||
// Default to "selected" behavior for backward compatibility
|
||||
if len(customAgent.Config.KnowledgeBases) > 0 {
|
||||
logger.Infof(ctx, "KBSelectionMode not set: using %d configured knowledge bases", len(customAgent.Config.KnowledgeBases))
|
||||
}
|
||||
return customAgent.Config.KnowledgeBases
|
||||
}
|
||||
}
|
||||
|
||||
// buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs.
|
||||
// tenantID is the retrieval scope: session.TenantID or effective tenant from shared agent (set by handler).
|
||||
// This is called once at the request entry point to avoid repeated queries later in the pipeline.
|
||||
// Logic:
|
||||
// - For each knowledgeBaseID: resolve actual TenantID (own, org-shared, or in retrieval-tenant scope for shared agent)
|
||||
// - For each knowledgeID: find its knowledgeBaseID; if the KB is already in the list, skip; otherwise add SearchTargetTypeKnowledge
|
||||
func (s *sessionService) buildSearchTargets(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
knowledgeBaseIDs []string,
|
||||
knowledgeIDs []string,
|
||||
) (types.SearchTargets, error) {
|
||||
var targets types.SearchTargets
|
||||
|
||||
// Build a map from KB ID to TenantID for all KBs we need to process
|
||||
kbTenantMap := make(map[string]uint64)
|
||||
|
||||
// Track which KBs are fully searched
|
||||
fullKBSet := make(map[string]bool)
|
||||
|
||||
// First pass: batch-fetch KBs, then resolve tenant per ID (tenant scope already set by caller)
|
||||
if len(knowledgeBaseIDs) > 0 {
|
||||
kbs, _ := s.knowledgeBaseService.GetKnowledgeBasesByIDsOnly(ctx, knowledgeBaseIDs)
|
||||
kbByID := make(map[string]*types.KnowledgeBase, len(kbs))
|
||||
for _, kb := range kbs {
|
||||
if kb != nil {
|
||||
kbByID[kb.ID] = kb
|
||||
}
|
||||
}
|
||||
userID, _ := types.UserIDFromContext(ctx)
|
||||
for _, kbID := range knowledgeBaseIDs {
|
||||
fullKBSet[kbID] = true
|
||||
kb := kbByID[kbID]
|
||||
if kb == nil {
|
||||
kbTenantMap[kbID] = tenantID
|
||||
} else if kb.TenantID == tenantID {
|
||||
kbTenantMap[kbID] = tenantID
|
||||
} else if s.kbShareService != nil && userID != "" {
|
||||
hasAccess, _ := s.kbShareService.HasKBPermission(ctx, kbID, userID, types.OrgRoleViewer)
|
||||
if hasAccess {
|
||||
kbTenantMap[kbID] = kb.TenantID
|
||||
} else {
|
||||
kbTenantMap[kbID] = tenantID
|
||||
}
|
||||
} else {
|
||||
kbTenantMap[kbID] = tenantID
|
||||
}
|
||||
targets = append(targets, &types.SearchTarget{
|
||||
Type: types.SearchTargetTypeKnowledgeBase,
|
||||
KnowledgeBaseID: kbID,
|
||||
TenantID: kbTenantMap[kbID],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Process individual knowledge IDs (include shared KB files the user has access to)
|
||||
if len(knowledgeIDs) > 0 {
|
||||
knowledgeList, err := s.knowledgeService.GetKnowledgeBatchWithSharedAccess(ctx, tenantID, knowledgeIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get knowledge batch for search targets: %v", err)
|
||||
return targets, nil // Return what we have, don't fail
|
||||
}
|
||||
|
||||
// Group knowledge IDs by their KB, excluding those already covered by full KB search
|
||||
// Also track KB tenant IDs from knowledge items
|
||||
kbToKnowledgeIDs := make(map[string][]string)
|
||||
for _, k := range knowledgeList {
|
||||
if k == nil || k.KnowledgeBaseID == "" {
|
||||
continue
|
||||
}
|
||||
// Track KB -> TenantID mapping from knowledge items
|
||||
if kbTenantMap[k.KnowledgeBaseID] == 0 {
|
||||
kbTenantMap[k.KnowledgeBaseID] = k.TenantID
|
||||
}
|
||||
// Skip if this KB is already fully searched
|
||||
if fullKBSet[k.KnowledgeBaseID] {
|
||||
continue
|
||||
}
|
||||
kbToKnowledgeIDs[k.KnowledgeBaseID] = append(kbToKnowledgeIDs[k.KnowledgeBaseID], k.ID)
|
||||
}
|
||||
|
||||
// Create SearchTargetTypeKnowledge targets for each KB with specific files
|
||||
for kbID, kidList := range kbToKnowledgeIDs {
|
||||
kbTenant := kbTenantMap[kbID]
|
||||
if kbTenant == 0 {
|
||||
kbTenant = tenantID // fallback
|
||||
}
|
||||
targets = append(targets, &types.SearchTarget{
|
||||
Type: types.SearchTargetTypeKnowledge,
|
||||
KnowledgeBaseID: kbID,
|
||||
TenantID: kbTenant,
|
||||
KnowledgeIDs: kidList,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Built %d search targets: %d full KB, %d partial KB, kbTenantMap=%v",
|
||||
len(targets), len(knowledgeBaseIDs), len(targets)-len(knowledgeBaseIDs), kbTenantMap)
|
||||
|
||||
return targets, nil
|
||||
}
|
||||
|
||||
// KnowledgeQAByEvent processes knowledge QA through a series of events in the pipeline
|
||||
func (s *sessionService) KnowledgeQAByEvent(ctx context.Context,
|
||||
chatManage *types.ChatManage, eventList []types.EventType,
|
||||
) error {
|
||||
ctx, span := tracing.ContextWithSpan(ctx, "SessionService.KnowledgeQAByEvent")
|
||||
defer span.End()
|
||||
|
||||
logger.Info(ctx, "Start processing knowledge base question answering through events")
|
||||
logger.Infof(ctx, "Knowledge base question answering parameters, session ID: %s, query: %s",
|
||||
chatManage.SessionID, chatManage.Query)
|
||||
|
||||
// Prepare method list for logging and tracing
|
||||
methods := []string{}
|
||||
for _, event := range eventList {
|
||||
methods = append(methods, string(event))
|
||||
}
|
||||
|
||||
// Set up tracing attributes
|
||||
logger.Infof(ctx, "Trigger event list: %v", methods)
|
||||
span.SetAttributes(
|
||||
attribute.String("request_id", func() string { id, _ := types.RequestIDFromContext(ctx); return id }()),
|
||||
attribute.String("query", chatManage.Query),
|
||||
attribute.String("method", strings.Join(methods, ",")),
|
||||
)
|
||||
|
||||
// Process each event in sequence
|
||||
for _, eventType := range eventList {
|
||||
logger.Infof(ctx, "Starting to trigger event: %v", eventType)
|
||||
err := s.eventManager.Trigger(ctx, eventType, chatManage)
|
||||
|
||||
// Handle case where search returns no results
|
||||
if err == chatpipline.ErrSearchNothing {
|
||||
logger.Warnf(
|
||||
ctx,
|
||||
"Event %v triggered, search result is empty, using fallback response, strategy: %v",
|
||||
eventType,
|
||||
chatManage.FallbackStrategy,
|
||||
)
|
||||
s.handleFallbackResponse(ctx, chatManage)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Handle other errors
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Event triggering failed, event: %v, error type: %s, description: %s, error: %v",
|
||||
eventType, err.ErrorType, err.Description, err.Err)
|
||||
span.RecordError(err.Err)
|
||||
span.SetStatus(codes.Error, err.Description)
|
||||
span.SetAttributes(attribute.String("error_type", err.ErrorType))
|
||||
return err.Err
|
||||
}
|
||||
logger.Infof(ctx, "Event %v triggered successfully", eventType)
|
||||
}
|
||||
|
||||
logger.Info(ctx, "All events triggered successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
// SearchKnowledge performs knowledge base search without LLM summarization
|
||||
// knowledgeBaseIDs: list of knowledge base IDs to search (supports multi-KB)
|
||||
// knowledgeIDs: list of specific knowledge (file) IDs to search
|
||||
func (s *sessionService) SearchKnowledge(ctx context.Context,
|
||||
knowledgeBaseIDs []string, knowledgeIDs []string, query string,
|
||||
) ([]*types.SearchResult, error) {
|
||||
logger.Info(ctx, "Start knowledge base search without LLM summary")
|
||||
logger.Infof(ctx, "Knowledge base search parameters, knowledge base IDs: %v, knowledge IDs: %v, query: %s",
|
||||
knowledgeBaseIDs, knowledgeIDs, query)
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, ok := types.TenantIDFromContext(ctx)
|
||||
if !ok {
|
||||
logger.Error(ctx, "Failed to get tenant ID from context")
|
||||
return nil, fmt.Errorf("tenant ID not found in context")
|
||||
}
|
||||
|
||||
// Build unified search targets (computed once, used throughout pipeline)
|
||||
searchTargets, err := s.buildSearchTargets(ctx, tenantID, knowledgeBaseIDs, knowledgeIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to build search targets: %v", err)
|
||||
}
|
||||
|
||||
if len(searchTargets) == 0 {
|
||||
logger.Warn(ctx, "No search targets available, returning empty results")
|
||||
return []*types.SearchResult{}, nil
|
||||
}
|
||||
|
||||
// Create default retrieval parameters — prefer tenant RetrievalConfig, fallback to built-in defaults
|
||||
userID, _ := types.UserIDFromContext(ctx)
|
||||
|
||||
// Load tenant-level retrieval config (nil is safe — GetEffective* methods handle nil receiver)
|
||||
var rc *types.RetrievalConfig
|
||||
if tenant, err2 := s.tenantService.GetTenantByID(ctx, tenantID); err2 == nil {
|
||||
rc = tenant.RetrievalConfig
|
||||
}
|
||||
|
||||
chatManage := &types.ChatManage{
|
||||
Query: query,
|
||||
RewriteQuery: query,
|
||||
UserID: userID,
|
||||
KnowledgeBaseIDs: knowledgeBaseIDs,
|
||||
KnowledgeIDs: knowledgeIDs,
|
||||
SearchTargets: searchTargets,
|
||||
MaxRounds: s.cfg.Conversation.MaxRounds,
|
||||
EmbeddingTopK: rc.GetEffectiveEmbeddingTopK(),
|
||||
VectorThreshold: rc.GetEffectiveVectorThreshold(),
|
||||
KeywordThreshold: rc.GetEffectiveKeywordThreshold(),
|
||||
RerankTopK: rc.GetEffectiveRerankTopK(),
|
||||
RerankThreshold: rc.GetEffectiveRerankThreshold(),
|
||||
}
|
||||
|
||||
// Get default models
|
||||
models, err := s.modelService.ListModels(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get models: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Use rerank model from RetrievalConfig if set, otherwise auto-select the first available
|
||||
if rc != nil && rc.RerankModelID != "" {
|
||||
chatManage.RerankModelID = rc.RerankModelID
|
||||
} else {
|
||||
for _, model := range models {
|
||||
if model == nil {
|
||||
continue
|
||||
}
|
||||
if model.Type == types.ModelTypeRerank {
|
||||
chatManage.RerankModelID = model.ID
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Use specific event list, only including retrieval-related events, not LLM summarization
|
||||
searchEvents := []types.EventType{
|
||||
types.CHUNK_SEARCH, // Vector search
|
||||
types.CHUNK_RERANK, // Rerank search results
|
||||
types.CHUNK_MERGE, // Merge search results
|
||||
types.FILTER_TOP_K, // Filter top K results
|
||||
}
|
||||
|
||||
ctx, span := tracing.ContextWithSpan(ctx, "SessionService.SearchKnowledge")
|
||||
defer span.End()
|
||||
|
||||
// Prepare method list for logging and tracing
|
||||
methods := []string{}
|
||||
for _, event := range searchEvents {
|
||||
methods = append(methods, string(event))
|
||||
}
|
||||
|
||||
// Set up tracing attributes
|
||||
logger.Infof(ctx, "Trigger search event list: %v", methods)
|
||||
span.SetAttributes(
|
||||
attribute.String("query", query),
|
||||
attribute.StringSlice("knowledge_base_ids", knowledgeBaseIDs),
|
||||
attribute.StringSlice("knowledge_ids", knowledgeIDs),
|
||||
attribute.String("method", strings.Join(methods, ",")),
|
||||
)
|
||||
|
||||
// Process each search event in sequence
|
||||
for _, event := range searchEvents {
|
||||
logger.Infof(ctx, "Starting to trigger search event: %v", event)
|
||||
err := s.eventManager.Trigger(ctx, event, chatManage)
|
||||
|
||||
// Handle case where search returns no results
|
||||
if err == chatpipline.ErrSearchNothing {
|
||||
logger.Warnf(ctx, "Event %v triggered, search result is empty", event)
|
||||
return []*types.SearchResult{}, nil
|
||||
}
|
||||
|
||||
// Handle other errors
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Event triggering failed, event: %v, error type: %s, description: %s, error: %v",
|
||||
event, err.ErrorType, err.Description, err.Err)
|
||||
span.RecordError(err.Err)
|
||||
span.SetStatus(codes.Error, err.Description)
|
||||
span.SetAttributes(attribute.String("error_type", err.ErrorType))
|
||||
return nil, err.Err
|
||||
}
|
||||
logger.Infof(ctx, "Event %v triggered successfully", event)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Knowledge base search completed, found %d results", len(chatManage.MergeResult))
|
||||
return chatManage.MergeResult, nil
|
||||
}
|
||||
|
||||
// handleFallbackResponse handles fallback response based on strategy
|
||||
func (s *sessionService) handleFallbackResponse(ctx context.Context, chatManage *types.ChatManage) {
|
||||
if chatManage.FallbackStrategy == types.FallbackStrategyModel {
|
||||
s.handleModelFallback(ctx, chatManage)
|
||||
} else {
|
||||
s.handleFixedFallback(ctx, chatManage)
|
||||
}
|
||||
}
|
||||
|
||||
// handleFixedFallback handles fixed fallback response
|
||||
func (s *sessionService) handleFixedFallback(ctx context.Context, chatManage *types.ChatManage) {
|
||||
fallbackContent := chatManage.FallbackResponse
|
||||
chatManage.ChatResponse = &types.ChatResponse{Content: fallbackContent}
|
||||
s.emitFallbackAnswer(ctx, chatManage, fallbackContent)
|
||||
}
|
||||
|
||||
// handleModelFallback handles model-based fallback response using streaming
|
||||
func (s *sessionService) handleModelFallback(ctx context.Context, chatManage *types.ChatManage) {
|
||||
// Check if FallbackPrompt is available
|
||||
if chatManage.FallbackPrompt == "" {
|
||||
logger.Warnf(ctx, "Fallback strategy is 'model' but FallbackPrompt is empty, falling back to fixed response")
|
||||
s.handleFixedFallback(ctx, chatManage)
|
||||
return
|
||||
}
|
||||
|
||||
// Render template with Query variable
|
||||
promptContent, err := s.renderFallbackPrompt(ctx, chatManage)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to render fallback prompt: %v, falling back to fixed response", err)
|
||||
s.handleFixedFallback(ctx, chatManage)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if EventBus is available for streaming
|
||||
if chatManage.EventBus == nil {
|
||||
logger.Warnf(ctx, "EventBus not available for streaming fallback, falling back to fixed response")
|
||||
s.handleFixedFallback(ctx, chatManage)
|
||||
return
|
||||
}
|
||||
|
||||
// Get chat model
|
||||
chatModel, err := s.modelService.GetChatModel(ctx, chatManage.ChatModelID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get chat model for fallback: %v, falling back to fixed response", err)
|
||||
s.handleFixedFallback(ctx, chatManage)
|
||||
return
|
||||
}
|
||||
|
||||
// Prepare chat options
|
||||
thinking := false
|
||||
opt := &chat.ChatOptions{
|
||||
Temperature: chatManage.SummaryConfig.Temperature,
|
||||
MaxCompletionTokens: chatManage.SummaryConfig.MaxCompletionTokens,
|
||||
Thinking: &thinking,
|
||||
}
|
||||
|
||||
// Start streaming response
|
||||
userMsg := chat.Message{Role: "user", Content: promptContent}
|
||||
if chatManage.ChatModelSupportsVision && len(chatManage.Images) > 0 {
|
||||
userMsg.Images = chatManage.Images
|
||||
}
|
||||
responseChan, err := chatModel.ChatStream(ctx, []chat.Message{userMsg}, opt)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to start streaming fallback response: %v, falling back to fixed response", err)
|
||||
s.handleFixedFallback(ctx, chatManage)
|
||||
return
|
||||
}
|
||||
|
||||
if responseChan == nil {
|
||||
logger.Errorf(ctx, "Chat stream returned nil channel, falling back to fixed response")
|
||||
s.handleFixedFallback(ctx, chatManage)
|
||||
return
|
||||
}
|
||||
|
||||
// Start goroutine to consume stream and emit events
|
||||
go s.consumeFallbackStream(ctx, chatManage, responseChan)
|
||||
}
|
||||
|
||||
// renderFallbackPrompt renders the fallback prompt template with query and image context.
|
||||
func (s *sessionService) renderFallbackPrompt(ctx context.Context, chatManage *types.ChatManage) (string, error) {
|
||||
query := chatManage.Query
|
||||
if rq := strings.TrimSpace(chatManage.RewriteQuery); rq != "" {
|
||||
query = rq
|
||||
}
|
||||
result := strings.ReplaceAll(chatManage.FallbackPrompt, "{{query}}", query)
|
||||
|
||||
if chatManage.ImageDescription != "" && !chatManage.ChatModelSupportsVision {
|
||||
result += "\n\n[用户上传图片内容]\n" + chatManage.ImageDescription
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// consumeFallbackStream consumes the streaming response and emits events
|
||||
func (s *sessionService) consumeFallbackStream(
|
||||
ctx context.Context,
|
||||
chatManage *types.ChatManage,
|
||||
responseChan <-chan types.StreamResponse,
|
||||
) {
|
||||
fallbackID := generateEventID("fallback")
|
||||
eventBus := chatManage.EventBus
|
||||
var finalContent string
|
||||
streamCompleted := false
|
||||
|
||||
for response := range responseChan {
|
||||
// Emit event for each answer chunk
|
||||
if response.ResponseType == types.ResponseTypeAnswer {
|
||||
finalContent += response.Content
|
||||
if err := eventBus.Emit(ctx, types.Event{
|
||||
ID: fallbackID,
|
||||
Type: types.EventType(event.EventAgentFinalAnswer),
|
||||
SessionID: chatManage.SessionID,
|
||||
Data: event.AgentFinalAnswerData{
|
||||
Content: response.Content,
|
||||
Done: response.Done,
|
||||
IsFallback: true,
|
||||
},
|
||||
}); err != nil {
|
||||
logger.Errorf(ctx, "Failed to emit fallback answer chunk event: %v", err)
|
||||
}
|
||||
|
||||
// Update ChatResponse with final content when done
|
||||
if response.Done {
|
||||
chatManage.ChatResponse = &types.ChatResponse{Content: finalContent}
|
||||
streamCompleted = true
|
||||
logger.Infof(ctx, "Fallback streaming response completed")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If channel closed without Done=true, emit final event with fixed response
|
||||
if !streamCompleted {
|
||||
logger.Warnf(ctx, "Fallback stream closed without completion, emitting final event with fixed response")
|
||||
s.emitFallbackAnswer(ctx, chatManage, chatManage.FallbackResponse)
|
||||
}
|
||||
}
|
||||
|
||||
// emitFallbackAnswer emits fallback answer event
|
||||
func (s *sessionService) emitFallbackAnswer(ctx context.Context, chatManage *types.ChatManage, content string) {
|
||||
if chatManage.EventBus == nil {
|
||||
return
|
||||
}
|
||||
|
||||
fallbackID := generateEventID("fallback")
|
||||
if err := chatManage.EventBus.Emit(ctx, types.Event{
|
||||
ID: fallbackID,
|
||||
Type: types.EventType(event.EventAgentFinalAnswer),
|
||||
SessionID: chatManage.SessionID,
|
||||
Data: event.AgentFinalAnswerData{
|
||||
Content: content,
|
||||
Done: true,
|
||||
IsFallback: true,
|
||||
},
|
||||
}); err != nil {
|
||||
logger.Errorf(ctx, "Failed to emit fallback answer event: %v", err)
|
||||
} else {
|
||||
logger.Infof(ctx, "Fallback answer event emitted successfully")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared QA helpers: KB resolution, model resolution, retrieval tenant
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// resolveKnowledgeBases resolves the effective knowledge base IDs and knowledge IDs
|
||||
// for a QA request. Priority:
|
||||
// 1. Explicit @mentions (request-specified kbIDs / knowledgeIDs)
|
||||
// 2. RetrieveKBOnlyWhenMentioned -> disable KB if no mention
|
||||
// 3. Agent's configured knowledge bases (via KBSelectionMode)
|
||||
func (s *sessionService) resolveKnowledgeBases(
|
||||
ctx context.Context,
|
||||
req *types.QARequest,
|
||||
) (kbIDs []string, knowledgeIDs []string) {
|
||||
kbIDs = req.KnowledgeBaseIDs
|
||||
knowledgeIDs = req.KnowledgeIDs
|
||||
customAgent := req.CustomAgent
|
||||
|
||||
hasExplicitMention := len(kbIDs) > 0 || len(knowledgeIDs) > 0
|
||||
if customAgent != nil {
|
||||
logger.Infof(ctx, "KB resolution: hasExplicitMention=%v, RetrieveKBOnlyWhenMentioned=%v, KBSelectionMode=%s",
|
||||
hasExplicitMention, customAgent.Config.RetrieveKBOnlyWhenMentioned, customAgent.Config.KBSelectionMode)
|
||||
}
|
||||
|
||||
if hasExplicitMention {
|
||||
logger.Infof(ctx, "Using request-specified targets: kbs=%v, docs=%v", kbIDs, knowledgeIDs)
|
||||
} else if customAgent != nil && customAgent.Config.RetrieveKBOnlyWhenMentioned {
|
||||
kbIDs = nil
|
||||
knowledgeIDs = nil
|
||||
logger.Infof(ctx, "RetrieveKBOnlyWhenMentioned is enabled and no @ mention found, KB retrieval disabled for this request")
|
||||
} else if customAgent != nil {
|
||||
kbIDs = s.resolveKnowledgeBasesFromAgent(ctx, customAgent, req.Session.TenantID)
|
||||
}
|
||||
return kbIDs, knowledgeIDs
|
||||
}
|
||||
|
||||
// resolveChatModelID resolves the effective chat model ID for a QA request.
|
||||
// Priority:
|
||||
// 1. Request's SummaryModelID (explicit override, validated)
|
||||
// 2. Custom agent's ModelID
|
||||
// 3. KB / session / system default (via selectChatModelID)
|
||||
func (s *sessionService) resolveChatModelID(
|
||||
ctx context.Context,
|
||||
req *types.QARequest,
|
||||
knowledgeBaseIDs []string,
|
||||
knowledgeIDs []string,
|
||||
) (string, error) {
|
||||
summaryModelID := req.SummaryModelID
|
||||
customAgent := req.CustomAgent
|
||||
session := req.Session
|
||||
|
||||
if summaryModelID != "" {
|
||||
if model, err := s.modelService.GetModelByID(ctx, summaryModelID); err == nil && model != nil {
|
||||
logger.Infof(ctx, "Using request's summary model override: %s", summaryModelID)
|
||||
return summaryModelID, nil
|
||||
}
|
||||
logger.Warnf(ctx, "Request provided invalid summary model ID %s, falling back", summaryModelID)
|
||||
}
|
||||
if customAgent != nil && customAgent.Config.ModelID != "" {
|
||||
logger.Infof(ctx, "Using custom agent's model_id: %s", customAgent.Config.ModelID)
|
||||
return customAgent.Config.ModelID, nil
|
||||
}
|
||||
return s.selectChatModelID(ctx, session, knowledgeBaseIDs, knowledgeIDs)
|
||||
}
|
||||
|
||||
// resolveRetrievalTenantID determines the tenant ID to use for retrieval scope.
|
||||
// Priority: agent's tenant > context tenant > session tenant.
|
||||
func (s *sessionService) resolveRetrievalTenantID(
|
||||
ctx context.Context,
|
||||
req *types.QARequest,
|
||||
) uint64 {
|
||||
session := req.Session
|
||||
customAgent := req.CustomAgent
|
||||
|
||||
retrievalTenantID := session.TenantID
|
||||
if customAgent != nil && customAgent.TenantID != 0 {
|
||||
retrievalTenantID = customAgent.TenantID
|
||||
logger.Infof(ctx, "Using agent tenant %d for retrieval scope", retrievalTenantID)
|
||||
} else if v := ctx.Value(types.TenantIDContextKey); v != nil {
|
||||
if tid, ok := v.(uint64); ok && tid != 0 {
|
||||
retrievalTenantID = tid
|
||||
logger.Infof(ctx, "Using effective tenant %d for retrieval from context", retrievalTenantID)
|
||||
}
|
||||
}
|
||||
return retrievalTenantID
|
||||
}
|
||||
|
||||
// applyAgentOverridesToChatManage applies custom agent configuration overrides
|
||||
// to a ChatManage object that was initialized with system defaults.
|
||||
// This covers: system prompt, context template, temperature, max tokens, thinking,
|
||||
// retrieval thresholds, rewrite settings, fallback settings, FAQ strategy, and history turns.
|
||||
func (s *sessionService) applyAgentOverridesToChatManage(
|
||||
ctx context.Context,
|
||||
customAgent *types.CustomAgent,
|
||||
cm *types.ChatManage,
|
||||
) {
|
||||
if customAgent == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Ensure defaults are set
|
||||
customAgent.EnsureDefaults()
|
||||
|
||||
// Override summary config fields
|
||||
if customAgent.Config.SystemPrompt != "" {
|
||||
cm.SummaryConfig.Prompt = customAgent.Config.SystemPrompt
|
||||
logger.Infof(ctx, "Using custom agent's system_prompt")
|
||||
}
|
||||
if customAgent.Config.ContextTemplate != "" {
|
||||
cm.SummaryConfig.ContextTemplate = customAgent.Config.ContextTemplate
|
||||
logger.Infof(ctx, "Using custom agent's context_template")
|
||||
}
|
||||
if customAgent.Config.Temperature > 0 {
|
||||
cm.SummaryConfig.Temperature = customAgent.Config.Temperature
|
||||
logger.Infof(ctx, "Using custom agent's temperature: %f", customAgent.Config.Temperature)
|
||||
}
|
||||
if customAgent.Config.MaxCompletionTokens > 0 {
|
||||
cm.SummaryConfig.MaxCompletionTokens = customAgent.Config.MaxCompletionTokens
|
||||
logger.Infof(ctx, "Using custom agent's max_completion_tokens: %d", customAgent.Config.MaxCompletionTokens)
|
||||
}
|
||||
// Agent-level thinking setting takes full control (no global fallback)
|
||||
cm.SummaryConfig.Thinking = customAgent.Config.Thinking
|
||||
if customAgent.Config.Thinking != nil {
|
||||
logger.Infof(ctx, "Using custom agent's thinking: %v", *customAgent.Config.Thinking)
|
||||
}
|
||||
|
||||
// Override retrieval strategy settings
|
||||
if customAgent.Config.EmbeddingTopK > 0 {
|
||||
cm.EmbeddingTopK = customAgent.Config.EmbeddingTopK
|
||||
}
|
||||
if customAgent.Config.KeywordThreshold > 0 {
|
||||
cm.KeywordThreshold = customAgent.Config.KeywordThreshold
|
||||
}
|
||||
if customAgent.Config.VectorThreshold > 0 {
|
||||
cm.VectorThreshold = customAgent.Config.VectorThreshold
|
||||
}
|
||||
if customAgent.Config.RerankTopK > 0 {
|
||||
cm.RerankTopK = customAgent.Config.RerankTopK
|
||||
}
|
||||
if customAgent.Config.RerankThreshold > 0 {
|
||||
cm.RerankThreshold = customAgent.Config.RerankThreshold
|
||||
}
|
||||
if customAgent.Config.RerankModelID != "" {
|
||||
cm.RerankModelID = customAgent.Config.RerankModelID
|
||||
}
|
||||
|
||||
// Override rewrite settings
|
||||
cm.EnableRewrite = customAgent.Config.EnableRewrite
|
||||
cm.EnableQueryExpansion = customAgent.Config.EnableQueryExpansion
|
||||
if customAgent.Config.RewritePromptSystem != "" {
|
||||
cm.RewritePromptSystem = customAgent.Config.RewritePromptSystem
|
||||
}
|
||||
if customAgent.Config.RewritePromptUser != "" {
|
||||
cm.RewritePromptUser = customAgent.Config.RewritePromptUser
|
||||
}
|
||||
|
||||
// Override fallback settings
|
||||
if customAgent.Config.FallbackStrategy != "" {
|
||||
cm.FallbackStrategy = types.FallbackStrategy(customAgent.Config.FallbackStrategy)
|
||||
}
|
||||
if customAgent.Config.FallbackResponse != "" {
|
||||
cm.FallbackResponse = customAgent.Config.FallbackResponse
|
||||
}
|
||||
if customAgent.Config.FallbackPrompt != "" {
|
||||
cm.FallbackPrompt = customAgent.Config.FallbackPrompt
|
||||
}
|
||||
|
||||
// Override history turns
|
||||
if customAgent.Config.HistoryTurns > 0 {
|
||||
cm.MaxRounds = customAgent.Config.HistoryTurns
|
||||
logger.Infof(ctx, "Using custom agent's history_turns: %d", cm.MaxRounds)
|
||||
}
|
||||
if !customAgent.Config.MultiTurnEnabled {
|
||||
cm.MaxRounds = 0
|
||||
logger.Infof(ctx, "Multi-turn disabled by custom agent, clearing history")
|
||||
}
|
||||
|
||||
// FAQ strategy settings
|
||||
cm.FAQPriorityEnabled = customAgent.Config.FAQPriorityEnabled
|
||||
cm.FAQDirectAnswerThreshold = customAgent.Config.FAQDirectAnswerThreshold
|
||||
cm.FAQScoreBoost = customAgent.Config.FAQScoreBoost
|
||||
if cm.FAQPriorityEnabled {
|
||||
logger.Infof(ctx, "FAQ priority enabled: threshold=%.2f, boost=%.2f",
|
||||
cm.FAQDirectAnswerThreshold, cm.FAQScoreBoost)
|
||||
}
|
||||
}
|
||||
+107
-83
@@ -38,6 +38,25 @@ type qaRequestContext struct {
|
||||
userMessageID string // Created user message ID (populated after createUserMessage)
|
||||
}
|
||||
|
||||
// buildQARequest converts the qaRequestContext into a types.QARequest for service invocation.
|
||||
func (rc *qaRequestContext) buildQARequest() *types.QARequest {
|
||||
imageURLs, imageDescription := extractImageURLsAndOCRText(rc.images)
|
||||
return &types.QARequest{
|
||||
Session: rc.session,
|
||||
Query: rc.query,
|
||||
AssistantMessageID: rc.assistantMessage.ID,
|
||||
SummaryModelID: rc.summaryModelID,
|
||||
CustomAgent: rc.customAgent,
|
||||
KnowledgeBaseIDs: rc.knowledgeBaseIDs,
|
||||
KnowledgeIDs: rc.knowledgeIDs,
|
||||
ImageURLs: imageURLs,
|
||||
ImageDescription: imageDescription,
|
||||
UserMessageID: rc.userMessageID,
|
||||
WebSearchEnabled: rc.webSearchEnabled,
|
||||
EnableMemory: rc.enableMemory,
|
||||
}
|
||||
}
|
||||
|
||||
// parseQARequest parses and validates a QA request, returns the request context
|
||||
func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestContext, *CreateKnowledgeQARequest, error) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
@@ -77,75 +96,10 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
||||
}
|
||||
|
||||
// Get custom agent if agent_id is provided. Backend resolves shared agent from share relation (no client-provided tenant).
|
||||
var customAgent *types.CustomAgent
|
||||
var effectiveTenantID uint64
|
||||
if request.AgentID != "" {
|
||||
logger.Infof(ctx, "Resolving agent, agent ID: %s", secutils.SanitizeForLog(request.AgentID))
|
||||
userIDVal, _ := c.Get(types.UserIDContextKey.String())
|
||||
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if h.agentShareService != nil && userIDVal != nil && currentTenantID != 0 {
|
||||
userID, _ := userIDVal.(string)
|
||||
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, request.AgentID)
|
||||
if err == nil && agent != nil {
|
||||
effectiveTenantID = agent.TenantID
|
||||
customAgent = agent
|
||||
logger.Infof(ctx, "Using shared agent: ID=%s, Name=%s, effectiveTenantID=%d (retrieval scope)",
|
||||
customAgent.ID, customAgent.Name, effectiveTenantID)
|
||||
}
|
||||
}
|
||||
if customAgent == nil {
|
||||
agent, err := h.customAgentService.GetAgentByID(ctx, request.AgentID)
|
||||
if err == nil {
|
||||
customAgent = agent
|
||||
logger.Infof(ctx, "Using own agent: ID=%s, Name=%s, AgentMode=%s",
|
||||
customAgent.ID, customAgent.Name, customAgent.Config.AgentMode)
|
||||
} else {
|
||||
logger.Warnf(ctx, "Failed to get custom agent, agent ID: %s, error: %v, using default config",
|
||||
secutils.SanitizeForLog(request.AgentID), err)
|
||||
}
|
||||
} else {
|
||||
logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s, effectiveTenantID=%d",
|
||||
customAgent.ID, customAgent.Name, customAgent.IsBuiltin, customAgent.Config.AgentMode, effectiveTenantID)
|
||||
}
|
||||
}
|
||||
customAgent, effectiveTenantID := h.resolveAgent(ctx, c, request.AgentID)
|
||||
|
||||
// Merge @mentioned items into knowledge_base_ids and knowledge_ids so that
|
||||
// retrieval (quick-answer and agent mode) uses the same targets the user @mentioned.
|
||||
// This fixes the case where user only @mentions a (shared) KB in the input but
|
||||
// does not select it in the sidebar — without this merge, retrieval would not search those KBs.
|
||||
kbIDs := make([]string, 0, len(request.KnowledgeBaseIDs)+len(request.MentionedItems))
|
||||
kbIDSet := make(map[string]bool)
|
||||
for _, id := range request.KnowledgeBaseIDs {
|
||||
if id != "" && !kbIDSet[id] {
|
||||
kbIDs = append(kbIDs, id)
|
||||
kbIDSet[id] = true
|
||||
}
|
||||
}
|
||||
knowledgeIDs := make([]string, 0, len(request.KnowledgeIds)+len(request.MentionedItems))
|
||||
knowledgeIDSet := make(map[string]bool)
|
||||
for _, id := range request.KnowledgeIds {
|
||||
if id != "" && !knowledgeIDSet[id] {
|
||||
knowledgeIDs = append(knowledgeIDs, id)
|
||||
knowledgeIDSet[id] = true
|
||||
}
|
||||
}
|
||||
for _, item := range request.MentionedItems {
|
||||
if item.ID == "" {
|
||||
continue
|
||||
}
|
||||
switch item.Type {
|
||||
case "kb":
|
||||
if !kbIDSet[item.ID] {
|
||||
kbIDs = append(kbIDs, item.ID)
|
||||
kbIDSet[item.ID] = true
|
||||
}
|
||||
case "file":
|
||||
if !knowledgeIDSet[item.ID] {
|
||||
knowledgeIDs = append(knowledgeIDs, item.ID)
|
||||
knowledgeIDSet[item.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
// Merge @mentioned items into knowledge_base_ids and knowledge_ids
|
||||
kbIDs, knowledgeIDs := mergeKnowledgeTargets(request.KnowledgeBaseIDs, request.KnowledgeIds, request.MentionedItems)
|
||||
|
||||
// Log merge results for debugging
|
||||
logger.Infof(ctx, "[%s] @mention merge: request.KnowledgeBaseIDs=%v, request.MentionedItems=%d, merged kbIDs=%v, merged knowledgeIDs=%v",
|
||||
@@ -200,6 +154,90 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
||||
return reqCtx, &request, nil
|
||||
}
|
||||
|
||||
// resolveAgent resolves the custom agent by ID, trying shared agent first, then own agent.
|
||||
// Returns (nil, 0) if agentID is empty or not found.
|
||||
func (h *Handler) resolveAgent(ctx context.Context, c *gin.Context, agentID string) (*types.CustomAgent, uint64) {
|
||||
if agentID == "" {
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Resolving agent, agent ID: %s", secutils.SanitizeForLog(agentID))
|
||||
|
||||
// Try shared agent first
|
||||
var customAgent *types.CustomAgent
|
||||
var effectiveTenantID uint64
|
||||
userIDVal, _ := c.Get(types.UserIDContextKey.String())
|
||||
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
|
||||
if h.agentShareService != nil && userIDVal != nil && currentTenantID != 0 {
|
||||
userID, _ := userIDVal.(string)
|
||||
agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID, currentTenantID, agentID)
|
||||
if err == nil && agent != nil {
|
||||
effectiveTenantID = agent.TenantID
|
||||
customAgent = agent
|
||||
logger.Infof(ctx, "Using shared agent: ID=%s, Name=%s, effectiveTenantID=%d (retrieval scope)",
|
||||
customAgent.ID, customAgent.Name, effectiveTenantID)
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to own agent
|
||||
if customAgent == nil {
|
||||
agent, err := h.customAgentService.GetAgentByID(ctx, agentID)
|
||||
if err == nil {
|
||||
customAgent = agent
|
||||
logger.Infof(ctx, "Using own agent: ID=%s, Name=%s, AgentMode=%s",
|
||||
customAgent.ID, customAgent.Name, customAgent.Config.AgentMode)
|
||||
} else {
|
||||
logger.Warnf(ctx, "Failed to get custom agent, agent ID: %s, error: %v, using default config",
|
||||
secutils.SanitizeForLog(agentID), err)
|
||||
}
|
||||
} else {
|
||||
logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s, effectiveTenantID=%d",
|
||||
customAgent.ID, customAgent.Name, customAgent.IsBuiltin, customAgent.Config.AgentMode, effectiveTenantID)
|
||||
}
|
||||
|
||||
return customAgent, effectiveTenantID
|
||||
}
|
||||
|
||||
// mergeKnowledgeTargets merges request KB/knowledge IDs with @mentioned items into deduplicated slices.
|
||||
func mergeKnowledgeTargets(requestKBIDs []string, requestKnowledgeIDs []string, mentionedItems []MentionedItemRequest) (kbIDs []string, knowledgeIDs []string) {
|
||||
kbIDSet := make(map[string]bool)
|
||||
kbIDs = make([]string, 0, len(requestKBIDs)+len(mentionedItems))
|
||||
for _, id := range requestKBIDs {
|
||||
if id != "" && !kbIDSet[id] {
|
||||
kbIDs = append(kbIDs, id)
|
||||
kbIDSet[id] = true
|
||||
}
|
||||
}
|
||||
|
||||
knowledgeIDSet := make(map[string]bool)
|
||||
knowledgeIDs = make([]string, 0, len(requestKnowledgeIDs)+len(mentionedItems))
|
||||
for _, id := range requestKnowledgeIDs {
|
||||
if id != "" && !knowledgeIDSet[id] {
|
||||
knowledgeIDs = append(knowledgeIDs, id)
|
||||
knowledgeIDSet[id] = true
|
||||
}
|
||||
}
|
||||
|
||||
for _, item := range mentionedItems {
|
||||
if item.ID == "" {
|
||||
continue
|
||||
}
|
||||
switch item.Type {
|
||||
case "kb":
|
||||
if !kbIDSet[item.ID] {
|
||||
kbIDs = append(kbIDs, item.ID)
|
||||
kbIDSet[item.ID] = true
|
||||
}
|
||||
case "file":
|
||||
if !knowledgeIDSet[item.ID] {
|
||||
knowledgeIDs = append(knowledgeIDs, item.ID)
|
||||
knowledgeIDSet[item.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return kbIDs, knowledgeIDs
|
||||
}
|
||||
|
||||
// sseStreamContext holds the context for SSE streaming
|
||||
type sseStreamContext struct {
|
||||
eventBus *event.EventBus
|
||||
@@ -511,21 +549,7 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle
|
||||
h.runVLMAnalysisIfNeeded(streamCtx, reqCtx, mode)
|
||||
|
||||
// Build QA request and invoke the appropriate service
|
||||
imageURLs, imageDescription := extractImageURLsAndOCRText(reqCtx.images)
|
||||
qaReq := &types.QARequest{
|
||||
Session: reqCtx.session,
|
||||
Query: reqCtx.query,
|
||||
AssistantMessageID: reqCtx.assistantMessage.ID,
|
||||
SummaryModelID: reqCtx.summaryModelID,
|
||||
CustomAgent: reqCtx.customAgent,
|
||||
KnowledgeBaseIDs: reqCtx.knowledgeBaseIDs,
|
||||
KnowledgeIDs: reqCtx.knowledgeIDs,
|
||||
ImageURLs: imageURLs,
|
||||
ImageDescription: imageDescription,
|
||||
UserMessageID: reqCtx.userMessageID,
|
||||
WebSearchEnabled: reqCtx.webSearchEnabled,
|
||||
EnableMemory: reqCtx.enableMemory,
|
||||
}
|
||||
qaReq := reqCtx.buildQARequest()
|
||||
|
||||
var serviceErr error
|
||||
var stageName string
|
||||
|
||||
Reference in New Issue
Block a user