feat: Implement FAQ functionality in Knowledge Base
- Added support for creating and managing FAQ knowledge bases, including new API endpoints for listing, upserting, updating, and deleting FAQ entries. - Enhanced the frontend to allow users to create FAQ knowledge bases and manage FAQ entries with a dedicated interface. - Introduced new types and configurations for FAQ handling in the backend, ensuring proper indexing and retrieval of FAQ entries. - Updated localization files to include new strings related to FAQ management in multiple languages. - Refactored existing components to accommodate the new FAQ features, improving user experience and functionality.
This commit is contained in:
@@ -25,7 +25,7 @@ func (r *chunkRepository) CreateChunks(ctx context.Context, chunks []*types.Chun
|
||||
for _, chunk := range chunks {
|
||||
chunk.Content = common.CleanInvalidUTF8(chunk.Content)
|
||||
}
|
||||
return r.db.WithContext(ctx).CreateInBatches(chunks, 100).Error
|
||||
return r.db.Debug().WithContext(ctx).CreateInBatches(chunks, 100).Error
|
||||
}
|
||||
|
||||
// GetChunkByID retrieves a chunk by its ID and tenant ID
|
||||
@@ -45,7 +45,7 @@ func (r *chunkRepository) ListChunksByID(
|
||||
ctx context.Context, tenantID uint, ids []string,
|
||||
) ([]*types.Chunk, error) {
|
||||
var chunks []*types.Chunk
|
||||
if err := r.db.WithContext(ctx).
|
||||
if err := r.db.Debug().WithContext(ctx).
|
||||
Where("tenant_id = ? AND id IN ?", tenantID, ids).
|
||||
Find(&chunks).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -77,15 +77,15 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
|
||||
|
||||
// First query the total count
|
||||
if err := r.db.WithContext(ctx).Model(&types.Chunk{}).
|
||||
Where("tenant_id = ? AND knowledge_id = ?", tenantID, knowledgeID).
|
||||
Where("tenant_id = ? AND knowledge_id = ? AND chunk_type IN (?)", tenantID, knowledgeID, chunk_type).
|
||||
Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Then query the paginated data
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info").
|
||||
Where("tenant_id = ? AND knowledge_id = ? and chunk_type in (?)", tenantID, knowledgeID, chunk_type).
|
||||
Select("id, content, knowledge_id, knowledge_base_id, start_at, end_at, chunk_index, is_enabled, chunk_type, parent_chunk_id, image_info, metadata").
|
||||
Where("tenant_id = ? AND knowledge_id = ? AND chunk_type IN (?)", tenantID, knowledgeID, chunk_type).
|
||||
Order("chunk_index ASC").
|
||||
Offset(page.Offset()).
|
||||
Limit(page.Limit()).
|
||||
|
||||
@@ -2021,6 +2021,668 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListFAQEntries lists FAQ entries under a FAQ knowledge base.
|
||||
func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
||||
kbID string, page *types.Pagination,
|
||||
) (*types.PageResult, error) {
|
||||
if page == nil {
|
||||
page = &types.Pagination{}
|
||||
}
|
||||
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
faqKnowledge, err := s.findFAQKnowledge(ctx, tenantID, kb.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if faqKnowledge == nil {
|
||||
return types.NewPageResult(0, page, []*types.FAQEntry{}), nil
|
||||
}
|
||||
chunkType := []types.ChunkType{types.ChunkTypeFAQ}
|
||||
chunks, total, err := s.chunkRepo.ListPagedChunksByKnowledgeID(
|
||||
ctx, tenantID, faqKnowledge.ID, page, chunkType,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kb.EnsureDefaults()
|
||||
entries := make([]*types.FAQEntry, 0, len(chunks))
|
||||
for _, chunk := range chunks {
|
||||
entry, err := s.chunkToFAQEntry(chunk, kb)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
return types.NewPageResult(total, page, entries), nil
|
||||
}
|
||||
|
||||
// UpsertFAQEntries imports or appends FAQ entries.
|
||||
func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,
|
||||
kbID string, payload *types.FAQBatchUpsertPayload,
|
||||
) error {
|
||||
if payload == nil || len(payload.Entries) == 0 {
|
||||
return werrors.NewBadRequestError("FAQ 条目不能为空")
|
||||
}
|
||||
if payload.Mode == "" {
|
||||
payload.Mode = types.FAQBatchModeAppend
|
||||
}
|
||||
if payload.Mode != types.FAQBatchModeAppend && payload.Mode != types.FAQBatchModeReplace {
|
||||
return werrors.NewBadRequestError("模式仅支持 append 或 replace")
|
||||
}
|
||||
|
||||
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
kb.EnsureDefaults()
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
faqKnowledge, err := s.ensureFAQKnowledge(ctx, tenantID, kb)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if payload.Mode == types.FAQBatchModeReplace {
|
||||
if err := s.cleanupFAQKnowledge(ctx, faqKnowledge); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
startIndex := 0
|
||||
if payload.Mode == types.FAQBatchModeAppend {
|
||||
_, total, err := s.chunkRepo.ListPagedChunksByKnowledgeID(ctx,
|
||||
tenantID,
|
||||
faqKnowledge.ID,
|
||||
&types.Pagination{Page: 1, PageSize: 1},
|
||||
[]types.ChunkType{types.ChunkTypeFAQ},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
startIndex = int(total)
|
||||
}
|
||||
|
||||
// 获取索引模式
|
||||
indexMode := types.FAQIndexModeQuestionOnly
|
||||
if kb.FAQConfig != nil && kb.FAQConfig.IndexMode != "" {
|
||||
indexMode = kb.FAQConfig.IndexMode
|
||||
}
|
||||
|
||||
chunks := make([]*types.Chunk, 0, len(payload.Entries))
|
||||
for idx := range payload.Entries {
|
||||
entry := payload.Entries[idx]
|
||||
meta, err := sanitizeFAQEntryPayload(&entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
chunk := &types.Chunk{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: tenantID,
|
||||
KnowledgeID: faqKnowledge.ID,
|
||||
KnowledgeBaseID: kb.ID,
|
||||
Content: buildFAQChunkContent(meta, indexMode),
|
||||
ChunkIndex: startIndex + idx + 1,
|
||||
IsEnabled: true,
|
||||
ChunkType: types.ChunkTypeFAQ,
|
||||
}
|
||||
if err := chunk.SetFAQMetadata(meta); err != nil {
|
||||
return err
|
||||
}
|
||||
chunks = append(chunks, chunk)
|
||||
}
|
||||
|
||||
if err := s.chunkService.CreateChunks(ctx, chunks); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.indexFAQChunks(ctx, kb, faqKnowledge, chunks, true); err != nil {
|
||||
for _, chunk := range chunks {
|
||||
_ = s.chunkService.DeleteChunk(ctx, chunk.ID)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateFAQEntry updates a single FAQ entry.
|
||||
func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,
|
||||
kbID string, entryID string, payload *types.FAQEntryPayload,
|
||||
) error {
|
||||
if payload == nil {
|
||||
return werrors.NewBadRequestError("请求体不能为空")
|
||||
}
|
||||
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
kb.EnsureDefaults()
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if chunk.KnowledgeBaseID != kb.ID {
|
||||
return werrors.NewForbiddenError("无权操作该 FAQ 条目")
|
||||
}
|
||||
if chunk.ChunkType != types.ChunkTypeFAQ {
|
||||
return werrors.NewBadRequestError("仅支持更新 FAQ 条目")
|
||||
}
|
||||
meta, err := sanitizeFAQEntryPayload(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing, err := chunk.FAQMetadata(); err == nil && existing != nil {
|
||||
meta.Version = existing.Version + 1
|
||||
}
|
||||
if err := chunk.SetFAQMetadata(meta); err != nil {
|
||||
return err
|
||||
}
|
||||
// 获取索引模式
|
||||
indexMode := types.FAQIndexModeQuestionOnly
|
||||
if kb.FAQConfig != nil && kb.FAQConfig.IndexMode != "" {
|
||||
indexMode = kb.FAQConfig.IndexMode
|
||||
}
|
||||
chunk.Content = buildFAQChunkContent(meta, indexMode)
|
||||
chunk.UpdatedAt = time.Now()
|
||||
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
|
||||
return err
|
||||
}
|
||||
faqKnowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, chunk.KnowledgeID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.indexFAQChunks(ctx, kb, faqKnowledge, []*types.Chunk{chunk}, false)
|
||||
}
|
||||
|
||||
// SearchFAQEntries searches FAQ entries using hybrid search.
|
||||
func (s *knowledgeService) SearchFAQEntries(ctx context.Context,
|
||||
kbID string, req *types.FAQSearchRequest,
|
||||
) ([]*types.FAQEntry, error) {
|
||||
// Validate FAQ knowledge base
|
||||
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Set default values
|
||||
if req.VectorThreshold <= 0 {
|
||||
req.VectorThreshold = 0.7
|
||||
}
|
||||
if req.MatchCount <= 0 {
|
||||
req.MatchCount = 10
|
||||
}
|
||||
if req.MatchCount > 50 {
|
||||
req.MatchCount = 50
|
||||
}
|
||||
|
||||
// Prepare search parameters
|
||||
searchParams := types.SearchParams{
|
||||
QueryText: req.QueryText,
|
||||
VectorThreshold: req.VectorThreshold,
|
||||
MatchCount: req.MatchCount,
|
||||
DisableKeywordsMatch: true,
|
||||
}
|
||||
|
||||
// Call HybridSearch
|
||||
searchResults, err := s.kbService.HybridSearch(ctx, kbID, searchParams)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(searchResults) == 0 {
|
||||
return []*types.FAQEntry{}, nil
|
||||
}
|
||||
|
||||
// Extract chunk IDs and build score/match type maps
|
||||
chunkIDs := make([]string, 0, len(searchResults))
|
||||
chunkScores := make(map[string]float64)
|
||||
chunkMatchTypes := make(map[string]types.MatchType)
|
||||
for _, result := range searchResults {
|
||||
// SearchResult.ID is the chunk ID
|
||||
chunkID := result.ID
|
||||
chunkIDs = append(chunkIDs, chunkID)
|
||||
chunkScores[chunkID] = result.Score
|
||||
chunkMatchTypes[chunkID] = result.MatchType
|
||||
}
|
||||
|
||||
// Batch fetch chunks
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
chunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Filter FAQ chunks and convert to FAQEntry
|
||||
kb.EnsureDefaults()
|
||||
entries := make([]*types.FAQEntry, 0, len(chunks))
|
||||
for _, chunk := range chunks {
|
||||
// Only process FAQ type chunks
|
||||
if chunk.ChunkType != types.ChunkTypeFAQ {
|
||||
continue
|
||||
}
|
||||
|
||||
entry, err := s.chunkToFAQEntry(chunk, kb)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to convert chunk to FAQ entry: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Preserve score and match type from search results
|
||||
// Note: Negative question filtering is now handled in HybridSearch
|
||||
if score, ok := chunkScores[chunk.ID]; ok {
|
||||
entry.Score = score
|
||||
}
|
||||
if matchType, ok := chunkMatchTypes[chunk.ID]; ok {
|
||||
entry.MatchType = matchType
|
||||
}
|
||||
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// DeleteFAQEntries deletes FAQ entries in batch.
|
||||
func (s *knowledgeService) DeleteFAQEntries(ctx context.Context,
|
||||
kbID string, entryIDs []string,
|
||||
) error {
|
||||
if len(entryIDs) == 0 {
|
||||
return werrors.NewBadRequestError("请选择需要删除的 FAQ 条目")
|
||||
}
|
||||
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
var faqKnowledge *types.Knowledge
|
||||
chunksToRemove := make([]*types.Chunk, 0, len(entryIDs))
|
||||
for _, id := range entryIDs {
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if chunk.KnowledgeBaseID != kb.ID || chunk.ChunkType != types.ChunkTypeFAQ {
|
||||
return werrors.NewBadRequestError("包含无效的 FAQ 条目")
|
||||
}
|
||||
if err := s.chunkService.DeleteChunk(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if faqKnowledge == nil {
|
||||
faqKnowledge, err = s.repo.GetKnowledgeByID(ctx, tenantID, chunk.KnowledgeID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
chunksToRemove = append(chunksToRemove, chunk)
|
||||
}
|
||||
if len(chunksToRemove) > 0 && faqKnowledge != nil {
|
||||
if err := s.deleteFAQChunkVectors(ctx, kb, faqKnowledge, chunksToRemove); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *knowledgeService) validateFAQKnowledgeBase(ctx context.Context, kbID string) (*types.KnowledgeBase, error) {
|
||||
if kbID == "" {
|
||||
return nil, werrors.NewBadRequestError("知识库 ID 不能为空")
|
||||
}
|
||||
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kb.EnsureDefaults()
|
||||
if kb.Type != types.KnowledgeBaseTypeFAQ {
|
||||
return nil, werrors.NewBadRequestError("仅 FAQ 知识库支持该操作")
|
||||
}
|
||||
return kb, nil
|
||||
}
|
||||
|
||||
func (s *knowledgeService) findFAQKnowledge(ctx context.Context, tenantID uint, kbID string) (*types.Knowledge, error) {
|
||||
knowledges, err := s.repo.ListKnowledgeByKnowledgeBaseID(ctx, tenantID, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, knowledge := range knowledges {
|
||||
if knowledge.Type == types.KnowledgeTypeFAQ {
|
||||
return knowledge, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *knowledgeService) ensureFAQKnowledge(ctx context.Context, tenantID uint, kb *types.KnowledgeBase) (*types.Knowledge, error) {
|
||||
existing, err := s.findFAQKnowledge(ctx, tenantID, kb.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existing != nil {
|
||||
return existing, nil
|
||||
}
|
||||
knowledge := &types.Knowledge{
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kb.ID,
|
||||
Type: types.KnowledgeTypeFAQ,
|
||||
Title: fmt.Sprintf("%s - FAQ", kb.Name),
|
||||
Description: "FAQ 条目容器",
|
||||
Source: types.KnowledgeTypeFAQ,
|
||||
ParseStatus: "completed",
|
||||
EnableStatus: "enabled",
|
||||
EmbeddingModelID: kb.EmbeddingModelID,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
if err := s.repo.CreateKnowledge(ctx, knowledge); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return knowledge, nil
|
||||
}
|
||||
|
||||
func (s *knowledgeService) chunkToFAQEntry(chunk *types.Chunk, kb *types.KnowledgeBase) (*types.FAQEntry, error) {
|
||||
meta, err := chunk.FAQMetadata()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if meta == nil {
|
||||
meta = &types.FAQChunkMetadata{StandardQuestion: chunk.Content}
|
||||
}
|
||||
entry := &types.FAQEntry{
|
||||
ID: chunk.ID,
|
||||
ChunkID: chunk.ID,
|
||||
KnowledgeID: chunk.KnowledgeID,
|
||||
KnowledgeBaseID: chunk.KnowledgeBaseID,
|
||||
StandardQuestion: meta.StandardQuestion,
|
||||
SimilarQuestions: meta.SimilarQuestions,
|
||||
NegativeQuestions: meta.NegativeQuestions,
|
||||
Answers: meta.Answers,
|
||||
IndexMode: kb.FAQConfig.IndexMode,
|
||||
UpdatedAt: chunk.UpdatedAt,
|
||||
CreatedAt: chunk.CreatedAt,
|
||||
ChunkType: chunk.ChunkType,
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
func buildFAQChunkContent(meta *types.FAQChunkMetadata, mode types.FAQIndexMode) string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString(fmt.Sprintf("Q: %s\n", meta.StandardQuestion))
|
||||
if len(meta.SimilarQuestions) > 0 {
|
||||
builder.WriteString("Similar Questions:\n")
|
||||
for _, q := range meta.SimilarQuestions {
|
||||
builder.WriteString(fmt.Sprintf("- %s\n", q))
|
||||
}
|
||||
}
|
||||
// 负例不应该包含在 Content 中,因为它们不应该被索引
|
||||
// 答案根据索引模式决定是否包含
|
||||
if mode == types.FAQIndexModeQuestionAnswer && len(meta.Answers) > 0 {
|
||||
builder.WriteString("Answers:\n")
|
||||
for _, ans := range meta.Answers {
|
||||
builder.WriteString(fmt.Sprintf("- %s\n", ans))
|
||||
}
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func sanitizeFAQEntryPayload(payload *types.FAQEntryPayload) (*types.FAQChunkMetadata, error) {
|
||||
meta := &types.FAQChunkMetadata{
|
||||
StandardQuestion: strings.TrimSpace(payload.StandardQuestion),
|
||||
SimilarQuestions: payload.SimilarQuestions,
|
||||
NegativeQuestions: payload.NegativeQuestions,
|
||||
Answers: payload.Answers,
|
||||
Version: 1,
|
||||
Source: "faq",
|
||||
}
|
||||
meta.Normalize()
|
||||
if meta.StandardQuestion == "" {
|
||||
return nil, werrors.NewBadRequestError("标准问不能为空")
|
||||
}
|
||||
if len(meta.Answers) == 0 {
|
||||
return nil, werrors.NewBadRequestError("至少提供一个答案")
|
||||
}
|
||||
return meta, nil
|
||||
}
|
||||
|
||||
func buildFAQIndexContent(meta *types.FAQChunkMetadata, mode types.FAQIndexMode) string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString(meta.StandardQuestion)
|
||||
for _, q := range meta.SimilarQuestions {
|
||||
builder.WriteString("\n")
|
||||
builder.WriteString(q)
|
||||
}
|
||||
if mode == types.FAQIndexModeQuestionAnswer {
|
||||
for _, ans := range meta.Answers {
|
||||
builder.WriteString("\n")
|
||||
builder.WriteString(ans)
|
||||
}
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// buildFAQIndexInfoList 构建FAQ索引信息列表,支持分别索引模式
|
||||
func (s *knowledgeService) buildFAQIndexInfoList(ctx context.Context, kb *types.KnowledgeBase, chunk *types.Chunk) ([]*types.IndexInfo, error) {
|
||||
indexMode := types.FAQIndexModeQuestionAnswer
|
||||
questionIndexMode := types.FAQQuestionIndexModeCombined
|
||||
if kb.FAQConfig != nil {
|
||||
if kb.FAQConfig.IndexMode != "" {
|
||||
indexMode = kb.FAQConfig.IndexMode
|
||||
}
|
||||
if kb.FAQConfig.QuestionIndexMode != "" {
|
||||
questionIndexMode = kb.FAQConfig.QuestionIndexMode
|
||||
}
|
||||
}
|
||||
logger.Infof(ctx, "buildFAQIndexInfoList: indexMode: %s, questionIndexMode: %s", indexMode, questionIndexMode)
|
||||
|
||||
meta, err := chunk.FAQMetadata()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if meta == nil {
|
||||
meta = &types.FAQChunkMetadata{StandardQuestion: chunk.Content}
|
||||
}
|
||||
|
||||
// 如果是一起索引模式,使用原有逻辑
|
||||
if questionIndexMode == types.FAQQuestionIndexModeCombined {
|
||||
content := buildFAQIndexContent(meta, indexMode)
|
||||
return []*types.IndexInfo{
|
||||
{
|
||||
Content: content,
|
||||
SourceID: chunk.ID,
|
||||
SourceType: types.ChunkSourceType,
|
||||
ChunkID: chunk.ID,
|
||||
KnowledgeID: chunk.KnowledgeID,
|
||||
KnowledgeBaseID: chunk.KnowledgeBaseID,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 分别索引模式:为每个问题创建独立的索引项
|
||||
indexInfoList := make([]*types.IndexInfo, 0)
|
||||
|
||||
// 标准问索引项
|
||||
standardContent := meta.StandardQuestion
|
||||
if indexMode == types.FAQIndexModeQuestionAnswer && len(meta.Answers) > 0 {
|
||||
var builder strings.Builder
|
||||
builder.WriteString(meta.StandardQuestion)
|
||||
for _, ans := range meta.Answers {
|
||||
builder.WriteString("\n")
|
||||
builder.WriteString(ans)
|
||||
}
|
||||
standardContent = builder.String()
|
||||
}
|
||||
indexInfoList = append(indexInfoList, &types.IndexInfo{
|
||||
Content: standardContent,
|
||||
SourceID: chunk.ID,
|
||||
SourceType: types.ChunkSourceType,
|
||||
ChunkID: chunk.ID,
|
||||
KnowledgeID: chunk.KnowledgeID,
|
||||
KnowledgeBaseID: chunk.KnowledgeBaseID,
|
||||
})
|
||||
|
||||
// 每个相似问创建一个索引项
|
||||
for i, similarQ := range meta.SimilarQuestions {
|
||||
similarContent := similarQ
|
||||
if indexMode == types.FAQIndexModeQuestionAnswer && len(meta.Answers) > 0 {
|
||||
var builder strings.Builder
|
||||
builder.WriteString(similarQ)
|
||||
for _, ans := range meta.Answers {
|
||||
builder.WriteString("\n")
|
||||
builder.WriteString(ans)
|
||||
}
|
||||
similarContent = builder.String()
|
||||
}
|
||||
sourceID := fmt.Sprintf("%s-%d", chunk.ID, i)
|
||||
indexInfoList = append(indexInfoList, &types.IndexInfo{
|
||||
Content: similarContent,
|
||||
SourceID: sourceID,
|
||||
SourceType: types.ChunkSourceType,
|
||||
ChunkID: chunk.ID,
|
||||
KnowledgeID: chunk.KnowledgeID,
|
||||
KnowledgeBaseID: chunk.KnowledgeBaseID,
|
||||
})
|
||||
}
|
||||
logger.Infof(ctx, "buildFAQIndexInfoList: indexInfoList: %v", indexInfoList)
|
||||
|
||||
return indexInfoList, nil
|
||||
}
|
||||
|
||||
func (s *knowledgeService) indexFAQChunks(ctx context.Context,
|
||||
kb *types.KnowledgeBase, knowledge *types.Knowledge, chunks []*types.Chunk, adjustStorage bool,
|
||||
) error {
|
||||
if len(chunks) == 0 {
|
||||
return nil
|
||||
}
|
||||
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
indexInfo := make([]*types.IndexInfo, 0)
|
||||
chunkIDs := make([]string, 0, len(chunks))
|
||||
for _, chunk := range chunks {
|
||||
infoList, err := s.buildFAQIndexInfoList(ctx, kb, chunk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
indexInfo = append(indexInfo, infoList...)
|
||||
chunkIDs = append(chunkIDs, chunk.ID)
|
||||
}
|
||||
|
||||
var size int64
|
||||
if adjustStorage {
|
||||
size = retrieveEngine.EstimateStorageSize(ctx, embeddingModel, indexInfo)
|
||||
if tenantInfo.StorageQuota > 0 && tenantInfo.StorageUsed+size > tenantInfo.StorageQuota {
|
||||
return types.NewStorageQuotaExceededError()
|
||||
}
|
||||
}
|
||||
|
||||
if err := retrieveEngine.DeleteByChunkIDList(ctx, chunkIDs, embeddingModel.GetDimensions()); err != nil {
|
||||
logger.Warnf(ctx, "Delete FAQ vectors failed: %v", err)
|
||||
}
|
||||
if err := retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfo); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if adjustStorage && size > 0 {
|
||||
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantInfo.ID, size); err == nil {
|
||||
tenantInfo.StorageUsed += size
|
||||
}
|
||||
knowledge.StorageSize += size
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
knowledge.UpdatedAt = now
|
||||
knowledge.ProcessedAt = &now
|
||||
return s.repo.UpdateKnowledge(ctx, knowledge)
|
||||
}
|
||||
|
||||
func (s *knowledgeService) deleteFAQChunkVectors(ctx context.Context,
|
||||
kb *types.KnowledgeBase, knowledge *types.Knowledge, chunks []*types.Chunk,
|
||||
) error {
|
||||
if len(chunks) == 0 {
|
||||
return nil
|
||||
}
|
||||
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
indexInfo := make([]*types.IndexInfo, 0)
|
||||
chunkIDs := make([]string, 0, len(chunks))
|
||||
for _, chunk := range chunks {
|
||||
infoList, err := s.buildFAQIndexInfoList(ctx, kb, chunk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
indexInfo = append(indexInfo, infoList...)
|
||||
chunkIDs = append(chunkIDs, chunk.ID)
|
||||
}
|
||||
|
||||
size := retrieveEngine.EstimateStorageSize(ctx, embeddingModel, indexInfo)
|
||||
if err := retrieveEngine.DeleteByChunkIDList(ctx, chunkIDs, embeddingModel.GetDimensions()); err != nil {
|
||||
return err
|
||||
}
|
||||
if size > 0 {
|
||||
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantInfo.ID, -size); err == nil {
|
||||
tenantInfo.StorageUsed -= size
|
||||
if tenantInfo.StorageUsed < 0 {
|
||||
tenantInfo.StorageUsed = 0
|
||||
}
|
||||
}
|
||||
if knowledge.StorageSize >= size {
|
||||
knowledge.StorageSize -= size
|
||||
} else {
|
||||
knowledge.StorageSize = 0
|
||||
}
|
||||
}
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
return s.repo.UpdateKnowledge(ctx, knowledge)
|
||||
}
|
||||
|
||||
func (s *knowledgeService) cleanupFAQKnowledge(ctx context.Context, knowledge *types.Knowledge) error {
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if knowledge.EmbeddingModelID != "" {
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
if err == nil {
|
||||
if embeddingModel, modelErr := s.modelService.GetEmbeddingModel(ctx, knowledge.EmbeddingModelID); modelErr == nil {
|
||||
_ = retrieveEngine.DeleteByKnowledgeIDList(ctx, []string{knowledge.ID}, embeddingModel.GetDimensions())
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := s.chunkService.DeleteChunksByKnowledgeID(ctx, knowledge.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if knowledge.StorageSize > 0 {
|
||||
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantInfo.ID, -knowledge.StorageSize); err == nil {
|
||||
tenantInfo.StorageUsed -= knowledge.StorageSize
|
||||
if tenantInfo.StorageUsed < 0 {
|
||||
tenantInfo.StorageUsed = 0
|
||||
}
|
||||
}
|
||||
knowledge.StorageSize = 0
|
||||
}
|
||||
knowledge.UpdatedAt = time.Now()
|
||||
knowledge.ProcessedAt = nil
|
||||
return s.repo.UpdateKnowledge(ctx, knowledge)
|
||||
}
|
||||
|
||||
func ensureManualFileName(title string) string {
|
||||
if title == "" {
|
||||
return fmt.Sprintf("manual-%s%s", time.Now().Format("20060102-150405"), manualFileExtension)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service/retriever"
|
||||
@@ -55,6 +56,7 @@ func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
|
||||
kb.CreatedAt = time.Now()
|
||||
kb.TenantID = ctx.Value(types.TenantIDContextKey).(uint)
|
||||
kb.UpdatedAt = time.Now()
|
||||
kb.EnsureDefaults()
|
||||
|
||||
logger.Infof(ctx, "Creating knowledge base, ID: %s, tenant ID: %d, name: %s", kb.ID, kb.TenantID, kb.Name)
|
||||
|
||||
@@ -87,6 +89,8 @@ func (s *knowledgeBaseService) GetKnowledgeBaseByID(ctx context.Context, id stri
|
||||
return nil, err
|
||||
}
|
||||
|
||||
kb.EnsureDefaults()
|
||||
|
||||
logger.Infof(ctx, "Knowledge base retrieved successfully, ID: %s, name: %s", kb.ID, kb.Name)
|
||||
return kb, nil
|
||||
}
|
||||
@@ -98,6 +102,10 @@ func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types
|
||||
|
||||
kbs, err := s.repo.ListKnowledgeBasesByTenantID(ctx, tenantID)
|
||||
if err != nil {
|
||||
for _, kb := range kbs {
|
||||
kb.EnsureDefaults()
|
||||
}
|
||||
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tenant_id": tenantID,
|
||||
})
|
||||
@@ -141,7 +149,12 @@ func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context,
|
||||
kb.Description = description
|
||||
kb.ChunkingConfig = config.ChunkingConfig
|
||||
kb.ImageProcessingConfig = config.ImageProcessingConfig
|
||||
// Update FAQ config if provided
|
||||
if config.FAQConfig != nil {
|
||||
kb.FAQConfig = config.FAQConfig
|
||||
}
|
||||
kb.UpdatedAt = time.Now()
|
||||
kb.EnsureDefaults()
|
||||
|
||||
logger.Info(ctx, "Saving knowledge base update")
|
||||
if err := s.repo.UpdateKnowledgeBase(ctx, kb); err != nil {
|
||||
@@ -232,6 +245,7 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
|
||||
logger.Errorf(ctx, "Get source knowledge base failed: %v", err)
|
||||
return nil, nil, err
|
||||
}
|
||||
sourceKB.EnsureDefaults()
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
var targetKB *types.KnowledgeBase
|
||||
if dstKB != "" {
|
||||
@@ -240,9 +254,15 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
|
||||
return nil, nil, err
|
||||
}
|
||||
} else {
|
||||
var faqConfig *types.FAQConfig
|
||||
if sourceKB.FAQConfig != nil {
|
||||
cfg := *sourceKB.FAQConfig
|
||||
faqConfig = &cfg
|
||||
}
|
||||
targetKB = &types.KnowledgeBase{
|
||||
ID: uuid.New().String(),
|
||||
Name: sourceKB.Name,
|
||||
Type: sourceKB.Type,
|
||||
Description: sourceKB.Description,
|
||||
TenantID: tenantID,
|
||||
ChunkingConfig: sourceKB.ChunkingConfig,
|
||||
@@ -252,7 +272,9 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
|
||||
RerankModelID: sourceKB.RerankModelID,
|
||||
VLMModelID: sourceKB.VLMModelID,
|
||||
StorageConfig: sourceKB.StorageConfig,
|
||||
FAQConfig: faqConfig,
|
||||
}
|
||||
targetKB.EnsureDefaults()
|
||||
if err := s.repo.CreateKnowledgeBase(ctx, targetKB); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -282,7 +304,7 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
||||
var kb *types.KnowledgeBase
|
||||
|
||||
// Add vector retrieval params if supported
|
||||
if retrieveEngine.SupportRetriever(types.VectorRetrieverType) {
|
||||
if retrieveEngine.SupportRetriever(types.VectorRetrieverType) && !params.DisableVectorMatch {
|
||||
logger.Info(ctx, "Vector retrieval supported, preparing vector retrieval parameters")
|
||||
|
||||
kb, err = s.repo.GetKnowledgeBaseByID(ctx, id)
|
||||
@@ -322,7 +344,7 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
||||
}
|
||||
|
||||
// Add keyword retrieval params if supported
|
||||
if retrieveEngine.SupportRetriever(types.KeywordsRetrieverType) {
|
||||
if retrieveEngine.SupportRetriever(types.KeywordsRetrieverType) && !params.DisableKeywordsMatch {
|
||||
logger.Info(ctx, "Keyword retrieval supported, preparing keyword retrieval parameters")
|
||||
retrieveParams = append(retrieveParams, types.RetrieveParams{
|
||||
Query: params.QueryText,
|
||||
@@ -367,15 +389,251 @@ func (s *knowledgeBaseService) HybridSearch(ctx context.Context,
|
||||
logger.Info(ctx, "No search results found")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Deduplicate results by chunk ID
|
||||
logger.Infof(ctx, "Result count before deduplication: %d", len(matchResults))
|
||||
deduplicatedChunks := common.Deduplicate(func(r *types.IndexWithScore) string { return r.ChunkID }, matchResults...)
|
||||
|
||||
for _, chunk := range matchResults {
|
||||
logger.Infof(ctx, "Before deduplication: Chunk: %s, Content: %s, Score: %f, MatchType: %d", chunk.ChunkID, chunk.Content, chunk.Score, chunk.MatchType)
|
||||
}
|
||||
|
||||
// First, try standard deduplication
|
||||
deduplicatedChunks := common.DeduplicateWithScore(func(r *types.IndexWithScore) string { return r.ChunkID }, matchResults...)
|
||||
logger.Infof(ctx, "Result count after deduplication: %d", len(deduplicatedChunks))
|
||||
for _, chunk := range deduplicatedChunks {
|
||||
logger.Infof(ctx, "After deduplication: Chunk: %s, Content: %s, Score: %f, MatchType: %d", chunk.ChunkID, chunk.Content, chunk.Score, chunk.MatchType)
|
||||
}
|
||||
|
||||
kb.EnsureDefaults()
|
||||
|
||||
// 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(deduplicatedChunks) < params.MatchCount &&
|
||||
kb.Type == types.KnowledgeBaseTypeFAQ &&
|
||||
kb.FAQConfig != nil &&
|
||||
kb.FAQConfig.QuestionIndexMode == types.FAQQuestionIndexModeSeparate
|
||||
|
||||
if needsIterativeRetrieval {
|
||||
logger.Infof(ctx, "Not enough unique chunks (%d < %d), using iterative retrieval for FAQ with separate indexing",
|
||||
len(deduplicatedChunks), params.MatchCount)
|
||||
// Use iterative retrieval to get more unique chunks (with negative question filtering inside)
|
||||
deduplicatedChunks = s.iterativeRetrieveWithDeduplication(ctx, retrieveEngine, retrieveParams, params.MatchCount, params.QueryText, kb.Type == types.KnowledgeBaseTypeFAQ)
|
||||
} else if kb.Type == types.KnowledgeBaseTypeFAQ {
|
||||
// Filter by negative questions if not using iterative retrieval
|
||||
deduplicatedChunks = s.filterByNegativeQuestions(ctx, deduplicatedChunks, params.QueryText)
|
||||
logger.Infof(ctx, "Result count after negative question filtering: %d", len(deduplicatedChunks))
|
||||
}
|
||||
|
||||
// Limit to MatchCount
|
||||
if len(deduplicatedChunks) > params.MatchCount {
|
||||
deduplicatedChunks = deduplicatedChunks[:params.MatchCount]
|
||||
}
|
||||
|
||||
return s.processSearchResults(ctx, deduplicatedChunks)
|
||||
}
|
||||
|
||||
// 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 to ensure we have enough valid chunks
|
||||
func (s *knowledgeBaseService) iterativeRetrieveWithDeduplication(ctx context.Context,
|
||||
retrieveEngine *retriever.CompositeRetrieveEngine,
|
||||
retrieveParams []types.RetrieveParams,
|
||||
matchCount int,
|
||||
queryText string,
|
||||
isFAQ bool,
|
||||
) []*types.IndexWithScore {
|
||||
maxIterations := 5
|
||||
currentTopK := matchCount
|
||||
uniqueChunks := make(map[string]*types.IndexWithScore)
|
||||
|
||||
for i := 0; i < maxIterations; i++ {
|
||||
logger.Infof(ctx, "Iterative retrieval iteration %d, TopK: %d", i+1, currentTopK)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// Check if we got fewer results than requested - means no more results available
|
||||
totalRetrieved := len(iterationResults)
|
||||
if totalRetrieved < currentTopK {
|
||||
logger.Infof(ctx, "Retrieved %d results (less than TopK %d), no more results available", totalRetrieved, currentTopK)
|
||||
}
|
||||
|
||||
// Deduplicate and merge (keep highest score for each chunk)
|
||||
// Multiple similar questions hitting the same chunk will keep the highest score
|
||||
for _, result := range iterationResults {
|
||||
if existing, ok := uniqueChunks[result.ChunkID]; !ok || result.Score > existing.Score {
|
||||
uniqueChunks[result.ChunkID] = result
|
||||
}
|
||||
}
|
||||
|
||||
// Convert to slice for filtering
|
||||
chunksSlice := make([]*types.IndexWithScore, 0, len(uniqueChunks))
|
||||
for _, chunk := range uniqueChunks {
|
||||
chunksSlice = append(chunksSlice, chunk)
|
||||
}
|
||||
|
||||
// Filter by negative questions if this is a FAQ knowledge base
|
||||
if isFAQ {
|
||||
chunksSlice = s.filterByNegativeQuestions(ctx, chunksSlice, queryText)
|
||||
// Update uniqueChunks map with filtered results
|
||||
uniqueChunks = make(map[string]*types.IndexWithScore, len(chunksSlice))
|
||||
for _, chunk := range chunksSlice {
|
||||
uniqueChunks[chunk.ChunkID] = chunk
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "After iteration %d: retrieved %d results, found %d unique chunks after filtering (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, stopping iteration")
|
||||
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)
|
||||
}
|
||||
|
||||
// Sort by score descending
|
||||
slices.SortFunc(result, func(a, b *types.IndexWithScore) int {
|
||||
if a.Score > b.Score {
|
||||
return -1
|
||||
} else if a.Score < b.Score {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
|
||||
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 := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// processSearchResults handles the processing of search results, optimizing database queries
|
||||
func (s *knowledgeBaseService) processSearchResults(ctx context.Context,
|
||||
chunks []*types.IndexWithScore,
|
||||
@@ -422,6 +680,7 @@ func (s *knowledgeBaseService) processSearchResults(ctx context.Context,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof(ctx, "Chunk data fetched successfully, count: %d", len(allChunks))
|
||||
|
||||
// Build chunk map and collect additional IDs to fetch
|
||||
chunkMap := make(map[string]*types.Chunk, len(allChunks))
|
||||
@@ -555,6 +814,7 @@ func (s *knowledgeBaseService) buildSearchResult(chunk *types.Chunk,
|
||||
func (s *knowledgeBaseService) isValidTextChunk(chunk *types.Chunk) bool {
|
||||
return slices.Contains([]types.ChunkType{
|
||||
types.ChunkTypeText, types.ChunkTypeSummary,
|
||||
types.ChunkTypeFAQ,
|
||||
}, chunk.ChunkType)
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ func (v *KeywordsVectorHybridRetrieveEngineService) Index(ctx context.Context,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
embeddingMap[indexInfo.ChunkID] = embedding
|
||||
embeddingMap[indexInfo.SourceID] = embedding
|
||||
}
|
||||
params["embedding"] = embeddingMap
|
||||
return v.indexRepository.Save(ctx, indexInfo, params)
|
||||
|
||||
@@ -645,14 +645,16 @@ func (s *sessionService) KnowledgeQAByEvent(ctx context.Context,
|
||||
fallbackID := generateEventID("fallback")
|
||||
if err := chatManage.EventBus.Emit(ctx, types.Event{
|
||||
ID: fallbackID,
|
||||
Type: types.EventType(event.EventAgentThought),
|
||||
Type: types.EventType(event.EventAgentFinalAnswer),
|
||||
SessionID: chatManage.SessionID,
|
||||
Data: event.AgentThoughtData{
|
||||
Data: event.AgentFinalAnswerData{
|
||||
Content: chatManage.FallbackResponse,
|
||||
Done: true,
|
||||
},
|
||||
}); err != nil {
|
||||
logger.Errorf(ctx, "Failed to emit fallback answer event: %v", err)
|
||||
} else {
|
||||
logger.Infof(ctx, "Fallback answer event emitted successfully")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
Reference in New Issue
Block a user