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:
wizardchen
2025-11-15 01:30:17 +08:00
parent 0ea5e6a2a2
commit 25fdaed8ca
37 changed files with 4778 additions and 198 deletions
+6
View File
@@ -201,6 +201,12 @@ Your pretraining data may be outdated or incorrect. Do NOT rely on any internal
<Thinking_and_Planning>
- IMPORTANT: Unless the user question is trivially simple (e.g., directly confirming visible information), you MUST use the thinking tool to break down complex problems, track thinking progress iteratively, and adjust the approach when retrieved content changes or exceptions block the original workflow.
- IMPORTANT: Record your KB-first compliance in the thinking step: briefly list the attempted KB strategies and why they were insufficient before you switch to web_search.
- CRITICAL - todo_write Tool Usage: The todo_write tool is MANDATORY and MUST be used frequently throughout your workflow. You MUST:
- Create a todo list at the START of any multi-step task (3+ steps) or complex problem-solving session.
- Update the todo list IMMEDIATELY after completing each task item (mark as completed).
- Add new todo items when you discover additional steps are needed.
- Mark items as in_progress when you start working on them.
- Use todo_write proactively to organize and track your progress; do NOT skip this tool even if you think you can handle the task without it. Regular todo management is essential for maintaining clarity and ensuring all tasks are completed.
- For multi-turn conversations, examine prior retrieved evidence first; if it cannot answer the new question, plan and execute fresh retrieval before responding.
- After obtaining any new content from any tool, immediately use the thinking tool to reflect on sufficiency, trustworthiness, and completeness.
- Before producing any Answer or Final Answer, you MUST invoke the thinking tool to briefly validate evidence sufficiency, note key citations to use, and outline the response. Do not emit the Answer until this thinking step is completed.
+122 -45
View File
@@ -609,6 +609,7 @@ func (t *KnowledgeSearchTool) rerankResults(
}
// rerankWithLLM uses LLM prompt to score and rerank search results
// Uses batch processing to handle large result sets efficiently
func (t *KnowledgeSearchTool) rerankWithLLM(
ctx context.Context,
query string,
@@ -616,75 +617,151 @@ func (t *KnowledgeSearchTool) rerankWithLLM(
) ([]*searchResultWithMeta, error) {
logger.Infof(ctx, "[Tool][KnowledgeSearch] Using LLM for reranking %d results", len(results))
// Build prompt with query and all passages
var passagesBuilder strings.Builder
for i, result := range results {
passagesBuilder.WriteString(fmt.Sprintf("Passage %d:\n%s\n\n", i+1, result.Content))
if len(results) == 0 {
return results, nil
}
prompt := fmt.Sprintf(`你是一个相关性评分专家。请根据查询问题,对以下每个段落进行相关性评分。
// Batch size: process 15 results at a time to balance quality and token usage
// This prevents token overflow and improves processing efficiency
const batchSize = 15
const maxContentLength = 800 // Maximum characters per passage to avoid excessive tokens
查询问题:%s
// Process in batches
allScores := make([]float64, len(results))
allReranked := make([]*searchResultWithMeta, 0, len(results))
评分要求:
1. 评分范围:0.0 到 1.0 之间的小数
2. 1.0 表示完全相关,0.0 表示完全不相关
3. 考虑语义相关性、信息完整性、准确性等因素
4. 必须为每个段落返回一个评分
5. 输出格式:每行一个评分,格式为 "Passage N: X.XX"(N 是段落编号,X.XX 是 0.0-1.0 之间的分数)
for batchStart := 0; batchStart < len(results); batchStart += batchSize {
batchEnd := batchStart + batchSize
if batchEnd > len(results) {
batchEnd = len(results)
}
段落列表:
batch := results[batchStart:batchEnd]
logger.Debugf(ctx, "[Tool][KnowledgeSearch] Processing rerank batch %d-%d of %d results",
batchStart+1, batchEnd, len(results))
// Build prompt with query and batch passages
var passagesBuilder strings.Builder
for i, result := range batch {
// Truncate content if too long to save tokens
content := result.Content
if len([]rune(content)) > maxContentLength {
runes := []rune(content)
content = string(runes[:maxContentLength]) + "..."
}
// Use clear separators to distinguish each passage
if i > 0 {
passagesBuilder.WriteString("\n")
}
passagesBuilder.WriteString("─────────────────────────────────────────────────────────────\n")
passagesBuilder.WriteString(fmt.Sprintf("Passage %d:\n", i+1))
passagesBuilder.WriteString("─────────────────────────────────────────────────────────────\n")
passagesBuilder.WriteString(content + "\n")
}
// Optimized prompt focused on retrieval matching and reranking
prompt := fmt.Sprintf(`You are a search result reranking expert. Your task is to evaluate how well each retrieved passage matches the user's search query and information need.
User Query: %s
Your task: Rerank these search results by evaluating their retrieval relevance - how well each passage answers or relates to the query.
Scoring Criteria (0.0 to 1.0):
- 1.0 (0.9-1.0): Directly answers the query, contains key information needed, highly relevant
- 0.8 (0.7-0.8): Strongly related, provides substantial relevant information
- 0.6 (0.5-0.6): Moderately related, contains some relevant information but may be incomplete
- 0.4 (0.3-0.4): Weakly related, minimal relevance to the query
- 0.2 (0.1-0.2): Barely related, mostly irrelevant
- 0.0 (0.0): Completely irrelevant, no relation to the query
Evaluation Factors:
1. Query-Answer Match: Does the passage directly address what the user is asking?
2. Information Completeness: Does it provide sufficient information to answer the query?
3. Semantic Relevance: Does the content semantically relate to the query intent?
4. Key Term Coverage: Does it cover important terms/concepts from the query?
5. Information Accuracy: Is the information accurate and trustworthy?
Retrieved Passages:
%s
请严格按照以下格式返回每个段落的评分(每行一个,共 %d 个):
IMPORTANT: Return exactly %d scores, one per line, in this exact format:
Passage 1: X.XX
Passage 2: X.XX
Passage 3: X.XX
...
Passage %d: X.XX`, query, passagesBuilder.String(), len(results), len(results))
Passage %d: X.XX
messages := []chat.Message{
{
Role: "system",
Content: "你是一个专业的文本相关性评分专家,能够准确评估文本与查询问题的相关性。",
},
{
Role: "user",
Content: prompt,
},
}
Output only the scores, no explanations or additional text.`, query, passagesBuilder.String(), len(batch), len(batch))
response, err := t.chatModel.Chat(ctx, messages, &chat.ChatOptions{
Temperature: 0.1, // Low temperature for consistent scoring
MaxTokens: 1024,
})
if err != nil {
return nil, fmt.Errorf("LLM rerank call failed: %w", err)
}
messages := []chat.Message{
{
Role: "system",
Content: "You are a professional search result reranking expert specializing in information retrieval. You evaluate how well retrieved passages match user queries in search scenarios. Focus on retrieval relevance: whether the passage answers the query, provides needed information, and matches the user's information need. Always respond with scores only, no explanations.",
},
{
Role: "user",
Content: prompt,
},
}
// Parse scores from response
scores, err := t.parseScoresFromResponse(response.Content, len(results))
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to parse LLM scores: %v, using original scores", err)
return results, nil // Return original results if parsing fails
// Calculate appropriate max tokens based on batch size
// Each score line is ~15 tokens, add buffer for safety
maxTokens := len(batch)*20 + 100
response, err := t.chatModel.Chat(ctx, messages, &chat.ChatOptions{
Temperature: 0.1, // Low temperature for consistent scoring
MaxTokens: maxTokens,
})
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] LLM rerank batch %d-%d failed: %v, using original scores",
batchStart+1, batchEnd, err)
// Use original scores for this batch on error
for i := batchStart; i < batchEnd; i++ {
allScores[i] = results[i].Score
}
continue
}
logger.Infof(ctx, "[Tool][KnowledgeSearch] LLM rerank batch %d-%d response: %s",
batchStart+1, batchEnd, response.Content)
// Parse scores from response
batchScores, err := t.parseScoresFromResponse(response.Content, len(batch))
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to parse LLM scores for batch %d-%d: %v, using original scores",
batchStart+1, batchEnd, err)
// Use original scores for this batch on parsing error
for i := batchStart; i < batchEnd; i++ {
allScores[i] = results[i].Score
}
continue
}
// Store scores for this batch
for i, score := range batchScores {
if batchStart+i < len(allScores) {
allScores[batchStart+i] = score
}
}
}
// Create reranked results with new scores
reranked := make([]*searchResultWithMeta, 0, len(results))
for i, result := range results {
newResult := *result
if i < len(scores) {
newResult.Score = scores[i]
if i < len(allScores) {
newResult.Score = allScores[i]
}
reranked = append(reranked, &newResult)
allReranked = append(allReranked, &newResult)
}
// Sort by new scores (descending)
sort.Slice(reranked, func(i, j int) bool {
return reranked[i].Score > reranked[j].Score
sort.Slice(allReranked, func(i, j int) bool {
return allReranked[i].Score > allReranked[j].Score
})
logger.Infof(ctx, "[Tool][KnowledgeSearch] LLM reranked %d results from %d original results", len(reranked), len(results))
return reranked, nil
logger.Infof(ctx, "[Tool][KnowledgeSearch] LLM reranked %d results from %d original results (processed in batches)",
len(allReranked), len(results))
return allReranked, nil
}
// parseScoresFromResponse parses scores from LLM response text
+5 -5
View File
@@ -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()).
+662
View File
@@ -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)
+265 -5
View File
@@ -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)
+4 -2
View File
@@ -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
+34
View File
@@ -49,6 +49,40 @@ func Deduplicate[T any, K comparable](keyFunc func(T) K, items ...T) []T {
return slices.Collect(maps.Values(seen))
}
// ScoreComparable is an interface for types that have a Score method returning float64
type ScoreComparable interface {
GetScore() float64
}
// DeduplicateWithScore removes duplicates from a slice based on a key function,
// keeping the item with the highest score for each key, then sorts by score descending
// T: the type of elements in the slice (must implement ScoreComparable)
// K: the type of key used for deduplication
func DeduplicateWithScore[T ScoreComparable, K comparable](keyFunc func(T) K, items ...T) []T {
seen := make(map[K]T)
for _, item := range items {
key := keyFunc(item)
if existing, exists := seen[key]; !exists {
seen[key] = item
} else if item.GetScore() > existing.GetScore() {
seen[key] = item
}
}
result := slices.Collect(maps.Values(seen))
// Sort by score descending
slices.SortFunc(result, func(a, b T) int {
scoreA := a.GetScore()
scoreB := b.GetScore()
if scoreA > scoreB {
return -1
} else if scoreA < scoreB {
return 1
}
return 0
})
return result
}
// ParseLLMJsonResponse parses a JSON response from LLM, handling cases where JSON is wrapped in code blocks.
// This is useful when LLMs return responses like:
// ```json
+1
View File
@@ -148,6 +148,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(handler.NewKnowledgeBaseHandler))
must(container.Provide(handler.NewKnowledgeHandler))
must(container.Provide(handler.NewChunkHandler))
must(container.Provide(handler.NewFAQHandler))
must(container.Provide(session.NewHandler))
must(container.Provide(handler.NewMessageHandler))
must(container.Provide(handler.NewModelHandler))
+135
View File
@@ -0,0 +1,135 @@
package handler
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// FAQHandler handles FAQ knowledge base operations.
type FAQHandler struct {
knowledgeService interfaces.KnowledgeService
}
// NewFAQHandler creates a new FAQ handler.
func NewFAQHandler(knowledgeService interfaces.KnowledgeService) *FAQHandler {
return &FAQHandler{knowledgeService: knowledgeService}
}
// ListEntries lists FAQ entries under a knowledge base.
func (h *FAQHandler) ListEntries(c *gin.Context) {
ctx := c.Request.Context()
var page types.Pagination
if err := c.ShouldBindQuery(&page); err != nil {
logger.Error(ctx, "Failed to bind pagination query", err)
c.Error(errors.NewBadRequestError("分页参数不合法").WithDetails(err.Error()))
return
}
result, err := h.knowledgeService.ListFAQEntries(ctx, c.Param("id"), &page)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": result,
})
}
// UpsertEntries appends or replaces FAQ entries in batch.
func (h *FAQHandler) UpsertEntries(c *gin.Context) {
ctx := c.Request.Context()
var req types.FAQBatchUpsertPayload
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ upsert payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if err := h.knowledgeService.UpsertFAQEntries(ctx, c.Param("id"), &req); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
})
}
// UpdateEntry updates a single FAQ entry.
func (h *FAQHandler) UpdateEntry(c *gin.Context) {
ctx := c.Request.Context()
var req types.FAQEntryPayload
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ entry payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if err := h.knowledgeService.UpdateFAQEntry(ctx, c.Param("id"), c.Param("entry_id"), &req); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
})
}
type faqDeleteRequest struct {
IDs []string `json:"ids" binding:"required,min=1,dive,required"`
}
// DeleteEntries deletes FAQ entries in batch.
func (h *FAQHandler) DeleteEntries(c *gin.Context) {
ctx := c.Request.Context()
var req faqDeleteRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ delete payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if err := h.knowledgeService.DeleteFAQEntries(ctx, c.Param("id"), req.IDs); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
})
}
// SearchFAQ searches FAQ entries using hybrid search.
func (h *FAQHandler) SearchFAQ(c *gin.Context) {
ctx := c.Request.Context()
var req types.FAQSearchRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ search payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
entries, err := h.knowledgeService.SearchFAQEntries(ctx, c.Param("id"), &req)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": entries,
})
}
+17
View File
@@ -41,6 +41,7 @@ type RouterParams struct {
SystemHandler *handler.SystemHandler
MCPServiceHandler *handler.MCPServiceHandler
WebSearchHandler *handler.WebSearchHandler
FAQHandler *handler.FAQHandler
}
// NewRouter 创建新的路由
@@ -79,6 +80,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterTenantRoutes(v1, params.TenantHandler)
RegisterKnowledgeBaseRoutes(v1, params.KBHandler)
RegisterKnowledgeRoutes(v1, params.KnowledgeHandler)
RegisterFAQRoutes(v1, params.FAQHandler)
RegisterChunkRoutes(v1, params.ChunkHandler)
RegisterSessionRoutes(v1, params.SessionHandler)
RegisterChatRoutes(v1, params.SessionHandler)
@@ -147,6 +149,21 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl
}
}
// RegisterFAQRoutes 注册 FAQ 相关路由
func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler) {
if handler == nil {
return
}
faq := r.Group("/knowledge-bases/:id/faq")
{
faq.GET("/entries", handler.ListEntries)
faq.POST("/entries", handler.UpsertEntries)
faq.PUT("/entries/:entry_id", handler.UpdateEntry)
faq.DELETE("/entries", handler.DeleteEntries)
faq.POST("/search", handler.SearchFAQ)
}
}
// RegisterKnowledgeBaseRoutes 注册知识库相关的路由
func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeBaseHandler) {
// 知识库路由组
+4
View File
@@ -24,6 +24,8 @@ const (
ChunkTypeEntity ChunkType = "entity"
// ChunkTypeRelationship 表示关系类型的 Chunk
ChunkTypeRelationship ChunkType = "relationship"
// ChunkTypeFAQ 表示 FAQ 条目 Chunk
ChunkTypeFAQ ChunkType = "faq"
)
// ImageInfo 表示与 Chunk 关联的图片信息
@@ -79,6 +81,8 @@ type Chunk struct {
RelationChunks JSON `json:"relation_chunks" gorm:"type:json"`
// 间接关系 Chunk ID,用于关联间接关系 Chunk 和原始文本 Chunk
IndirectRelationChunks JSON `json:"indirect_relation_chunks" gorm:"type:json"`
// Metadata 存储 chunk 级别的扩展信息,例如 FAQ 元数据
Metadata JSON `json:"metadata" gorm:"type:json"`
// 图片信息,存储为 JSON
ImageInfo string `json:"image_info" gorm:"type:text"`
// Chunk creation time
+130
View File
@@ -0,0 +1,130 @@
package types
import (
"encoding/json"
"strings"
"time"
)
// FAQChunkMetadata 定义 FAQ 条目在 Chunk.Metadata 中的结构
type FAQChunkMetadata struct {
StandardQuestion string `json:"standard_question"`
SimilarQuestions []string `json:"similar_questions,omitempty"`
NegativeQuestions []string `json:"negative_questions,omitempty"`
Answers []string `json:"answers,omitempty"`
Version int `json:"version,omitempty"`
Source string `json:"source,omitempty"`
}
// Normalize 清理空白与重复项
func (m *FAQChunkMetadata) Normalize() {
if m == nil {
return
}
m.StandardQuestion = strings.TrimSpace(m.StandardQuestion)
m.SimilarQuestions = normalizeStrings(m.SimilarQuestions)
m.NegativeQuestions = normalizeStrings(m.NegativeQuestions)
m.Answers = normalizeStrings(m.Answers)
if m.Version <= 0 {
m.Version = 1
}
}
// FAQMetadata 解析 Chunk 中的 FAQ 元数据
func (c *Chunk) FAQMetadata() (*FAQChunkMetadata, error) {
if c == nil || len(c.Metadata) == 0 {
return nil, nil
}
var meta FAQChunkMetadata
if err := json.Unmarshal(c.Metadata, &meta); err != nil {
return nil, err
}
meta.Normalize()
return &meta, nil
}
// SetFAQMetadata 设置 Chunk 的 FAQ 元数据
func (c *Chunk) SetFAQMetadata(meta *FAQChunkMetadata) error {
if c == nil {
return nil
}
if meta == nil {
c.Metadata = nil
return nil
}
meta.Normalize()
bytes, err := json.Marshal(meta)
if err != nil {
return err
}
c.Metadata = JSON(bytes)
return nil
}
// FAQEntry 表示返回给前端的 FAQ 条目
type FAQEntry struct {
ID string `json:"id"`
ChunkID string `json:"chunk_id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
StandardQuestion string `json:"standard_question"`
SimilarQuestions []string `json:"similar_questions"`
NegativeQuestions []string `json:"negative_questions"`
Answers []string `json:"answers"`
IndexMode FAQIndexMode `json:"index_mode"`
UpdatedAt time.Time `json:"updated_at"`
CreatedAt time.Time `json:"created_at"`
Score float64 `json:"score,omitempty"`
MatchType MatchType `json:"match_type,omitempty"`
ChunkType ChunkType `json:"chunk_type"`
}
// FAQEntryPayload 用于创建/更新 FAQ 条目的 payload
type FAQEntryPayload struct {
StandardQuestion string `json:"standard_question" binding:"required"`
SimilarQuestions []string `json:"similar_questions"`
NegativeQuestions []string `json:"negative_questions"`
Answers []string `json:"answers" binding:"required"`
}
const (
FAQBatchModeAppend = "append"
FAQBatchModeReplace = "replace"
)
// FAQBatchUpsertPayload 批量导入 FAQ 条目
type FAQBatchUpsertPayload struct {
Entries []FAQEntryPayload `json:"entries" binding:"required"`
Mode string `json:"mode" binding:"oneof=append replace"`
KnowledgeID string `json:"knowledge_id"`
}
// FAQSearchRequest FAQ检索请求参数
type FAQSearchRequest struct {
QueryText string `json:"query_text" binding:"required"`
VectorThreshold float64 `json:"vector_threshold"`
MatchCount int `json:"match_count"`
}
func normalizeStrings(values []string) []string {
if len(values) == 0 {
return nil
}
dedup := make([]string, 0, len(values))
seen := make(map[string]struct{}, len(values))
for _, v := range values {
trimmed := strings.TrimSpace(v)
if trimmed == "" {
continue
}
if _, exists := seen[trimmed]; exists {
continue
}
seen[trimmed] = struct{}{}
dedup = append(dedup, trimmed)
}
if len(dedup) == 0 {
return nil
}
return dedup
}
+10
View File
@@ -50,6 +50,16 @@ type KnowledgeService interface {
CloneKnowledgeBase(ctx context.Context, srcID, dstID string) error
// UpdateImageInfo updates image information for a knowledge chunk.
UpdateImageInfo(ctx context.Context, knowledgeID string, chunkID string, imageInfo string) error
// ListFAQEntries lists FAQ entries under a FAQ knowledge base.
ListFAQEntries(ctx context.Context, kbID string, page *types.Pagination) (*types.PageResult, error)
// UpsertFAQEntries imports or appends FAQ entries.
UpsertFAQEntries(ctx context.Context, kbID string, payload *types.FAQBatchUpsertPayload) error
// UpdateFAQEntry updates a single FAQ entry.
UpdateFAQEntry(ctx context.Context, kbID string, entryID string, payload *types.FAQEntryPayload) error
// DeleteFAQEntries deletes FAQ entries in batch.
DeleteFAQEntries(ctx context.Context, kbID string, entryIDs []string) error
// SearchFAQEntries searches FAQ entries using hybrid search.
SearchFAQEntries(ctx context.Context, kbID string, req *types.FAQSearchRequest) ([]*types.FAQEntry, error)
}
// KnowledgeRepository defines the interface for knowledge repositories.
+1
View File
@@ -11,6 +11,7 @@ import (
const (
KnowledgeTypeManual = "manual"
KnowledgeTypeFAQ = "faq"
)
const (
+81
View File
@@ -12,12 +12,39 @@ const (
InitDefaultKnowledgeBaseID = "kb-00000001"
)
const (
KnowledgeBaseTypeDocument = "document"
KnowledgeBaseTypeFAQ = "faq"
)
// FAQIndexMode 表示 FAQ 索引策略:仅索引标准问还是同时索引问答内容
type FAQIndexMode string
const (
// FAQIndexModeQuestionOnly 仅使用标准问及相似问向量化
FAQIndexModeQuestionOnly FAQIndexMode = "question_only"
// FAQIndexModeQuestionAnswer 将标准问与答案拼接后向量化
FAQIndexModeQuestionAnswer FAQIndexMode = "question_answer"
)
// FAQQuestionIndexMode 表示 FAQ 问题索引方式:一起索引还是分别索引
type FAQQuestionIndexMode string
const (
// FAQQuestionIndexModeCombined 将标准问和相似问一起索引(当前方式)
FAQQuestionIndexModeCombined FAQQuestionIndexMode = "combined"
// FAQQuestionIndexModeSeparate 将标准问和相似问分别索引
FAQQuestionIndexModeSeparate FAQQuestionIndexMode = "separate"
)
// KnowledgeBase represents a knowledge base
type KnowledgeBase struct {
// Unique identifier of the knowledge base
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"`
// Name of the knowledge base
Name string `yaml:"name" json:"name"`
// Type of the knowledge base (document, faq, etc.)
Type string `yaml:"type" json:"type" gorm:"type:varchar(32);default:'document'"`
// Whether this knowledge base is temporary (ephemeral) and should be hidden from UI
IsTemporary bool `yaml:"is_temporary" json:"is_temporary" gorm:"default:false"`
// Description of the knowledge base
@@ -42,6 +69,8 @@ type KnowledgeBase struct {
StorageConfig StorageConfig `yaml:"cos_config" json:"cos_config" gorm:"column:cos_config;type:json"`
// Extract config
ExtractConfig *ExtractConfig `yaml:"extract_config" json:"extract_config" gorm:"column:extract_config;type:json"`
// FAQConfig stores FAQ specific configuration such as indexing strategy
FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config" gorm:"column:faq_config;type:json"`
// Creation time of the knowledge base
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time of the knowledge base
@@ -56,6 +85,8 @@ type KnowledgeBaseConfig struct {
ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config"`
// Image processing configuration
ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config"`
// FAQ configuration (only for FAQ type knowledge bases)
FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config"`
}
// ChunkingConfig represents the document splitting configuration
@@ -195,3 +226,53 @@ func (e *ExtractConfig) Scan(value interface{}) error {
}
return json.Unmarshal(b, e)
}
// FAQConfig 存储 FAQ 知识库的特有配置
type FAQConfig struct {
IndexMode FAQIndexMode `yaml:"index_mode" json:"index_mode"`
QuestionIndexMode FAQQuestionIndexMode `yaml:"question_index_mode" json:"question_index_mode"`
}
// Value implements driver.Valuer
func (f FAQConfig) Value() (driver.Value, error) {
return json.Marshal(f)
}
// Scan implements sql.Scanner
func (f *FAQConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, f)
}
// EnsureDefaults 确保类型与配置具备默认值
func (kb *KnowledgeBase) EnsureDefaults() {
if kb == nil {
return
}
if kb.Type == "" {
kb.Type = KnowledgeBaseTypeDocument
}
if kb.Type != KnowledgeBaseTypeFAQ {
kb.FAQConfig = nil
return
}
if kb.FAQConfig == nil {
kb.FAQConfig = &FAQConfig{
IndexMode: FAQIndexModeQuestionAnswer,
QuestionIndexMode: FAQQuestionIndexModeCombined,
}
return
}
if kb.FAQConfig.IndexMode == "" {
kb.FAQConfig.IndexMode = FAQIndexModeQuestionAnswer
}
if kb.FAQConfig.QuestionIndexMode == "" {
kb.FAQConfig.QuestionIndexMode = FAQQuestionIndexModeCombined
}
}
+5
View File
@@ -73,6 +73,11 @@ type IndexWithScore struct {
MatchType MatchType
}
// GetScore returns the score for ScoreComparable interface
func (i *IndexWithScore) GetScore() float64 {
return i.Score
}
// RetrieveResult represents the result of retrieval
type RetrieveResult struct {
Results []*IndexWithScore // Retrieval results
+6 -4
View File
@@ -50,10 +50,12 @@ type SearchResult struct {
// SearchParams represents the search parameters
type SearchParams struct {
QueryText string `json:"query_text"`
VectorThreshold float64 `json:"vector_threshold"`
KeywordThreshold float64 `json:"keyword_threshold"`
MatchCount int `json:"match_count"`
QueryText string `json:"query_text"`
VectorThreshold float64 `json:"vector_threshold"`
KeywordThreshold float64 `json:"keyword_threshold"`
MatchCount int `json:"match_count"`
DisableKeywordsMatch bool `json:"disable_keywords_match"`
DisableVectorMatch bool `json:"disable_vector_match"`
}
// Value implements the driver.Valuer interface, used to convert SearchResult to database value