Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat: 支持向 FAQ 条目添加相似问
wizardchen9338603c20c6
diff --git a/client/faq.go b/client/faq.goindex d082f971a..116ba8399 100644--- a/client/faq.go+++ b/client/faq.go@@ -263,6 +263,29 @@ func (c *Client) UpdateFAQEntry(ctx context.Context,return response.Data, nil}+// AddSimilarQuestionsPayload is used to add similar questions to a FAQ entry.+type AddSimilarQuestionsPayload struct {+ SimilarQuestions []string `json:"similar_questions"`+}++// AddSimilarQuestions adds similar questions to a FAQ entry.+// This will append the new questions to the existing similar questions list.+func (c *Client) AddSimilarQuestions(ctx context.Context,+ knowledgeBaseID string, entrySeqID int64, payload *AddSimilarQuestionsPayload,+) (*FAQEntry, error) {+ path := fmt.Sprintf("/api/v1/knowledge-bases/%s/faq/entries/%d/similar-questions", knowledgeBaseID, entrySeqID)+ resp, err := c.doRequest(ctx, http.MethodPost, path, payload, nil)+ if err != nil {+ return nil, err+ }++ var response FAQEntryResponse+ if err := parseResponse(resp, &response); err != nil {+ return nil, err+ }+ return response.Data, nil+}+// UpdateFAQEntryFieldsBatch updates multiple fields for FAQ entries in bulk.// Supports updating is_enabled, is_recommended, tag_id in a single call.// Supports two modes:diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.goindex 91fd6cb58..941ff04a5 100644--- a/internal/application/service/knowledge.go+++ b/internal/application/service/knowledge.go@@ -3978,6 +3978,170 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,return entry, nil}+// AddSimilarQuestions adds similar questions to a FAQ entry.+// This will append the new questions to the existing similar questions list.+func (s *knowledgeService) AddSimilarQuestions(ctx context.Context,+ kbID string, entrySeqID int64, questions []string,+) (*types.FAQEntry, error) {+ if len(questions) == 0 {+ return nil, werrors.NewBadRequestError("相似问列表不能为空")+ }++ kb, err := s.validateFAQKnowledgeBase(ctx, kbID)+ if err != nil {+ return nil, err+ }+ kb.EnsureDefaults()+ tenantID := ctx.Value(types.TenantIDContextKey).(uint64)++ // Get existing FAQ entry+ chunk, err := s.chunkRepo.GetChunkBySeqID(ctx, tenantID, entrySeqID)+ if err != nil {+ return nil, werrors.NewNotFoundError("FAQ条目不存在")+ }+ if chunk.KnowledgeBaseID != kb.ID {+ return nil, werrors.NewForbiddenError("无权操作该 FAQ 条目")+ }+ if chunk.ChunkType != types.ChunkTypeFAQ {+ return nil, werrors.NewBadRequestError("仅支持更新 FAQ 条目")+ }++ // Get existing metadata+ meta, err := chunk.FAQMetadata()+ if err != nil || meta == nil {+ return nil, werrors.NewBadRequestError("获取 FAQ 元数据失败")+ }++ // Deduplicate and sanitize new questions+ existingSet := make(map[string]struct{})+ for _, q := range meta.SimilarQuestions {+ existingSet[q] = struct{}{}+ }+ // Also add standard question to prevent duplicates+ existingSet[meta.StandardQuestion] = struct{}{}++ newQuestions := make([]string, 0, len(questions))+ for _, q := range questions {+ q = strings.TrimSpace(q)+ if q == "" {+ continue+ }+ if _, exists := existingSet[q]; exists {+ continue+ }+ existingSet[q] = struct{}{}+ newQuestions = append(newQuestions, q)+ }++ if len(newQuestions) == 0 {+ // No new questions to add, return current entry+ tagSeqIDMap := make(map[string]int64)+ if chunk.TagID != "" {+ tag, tagErr := s.tagRepo.GetByID(ctx, tenantID, chunk.TagID)+ if tagErr == nil && tag != nil {+ tagSeqIDMap[tag.ID] = tag.SeqID+ }+ }+ return s.chunkToFAQEntry(chunk, kb, tagSeqIDMap)+ }++ // Security check for new questions using CheckFAQContent+ tempPayload := &types.FAQEntryPayload{+ StandardQuestion: meta.StandardQuestion,+ SimilarQuestions: newQuestions,+ Answers: meta.Answers,+ }+ blockStatus, checkErr := s.CheckFAQContent(ctx, tenantID, tempPayload)+ if checkErr != nil {+ logger.Warnf(ctx, "AddSimilarQuestions: security check error: %v", checkErr)+ }+ if blockStatus != 0 {+ return nil, werrors.NewBadRequestError("相似问内容违规,请调整后重试")+ }++ // Check for duplicates with other entries+ tempMeta := &types.FAQChunkMetadata{+ StandardQuestion: meta.StandardQuestion,+ SimilarQuestions: append(meta.SimilarQuestions, newQuestions...),+ }+ if err := s.checkFAQQuestionDuplicate(ctx, tenantID, kb.ID, chunk.ID, tempMeta); err != nil {+ return nil, err+ }++ // Update metadata+ oldSimilarQuestions := meta.SimilarQuestions+ meta.SimilarQuestions = append(meta.SimilarQuestions, newQuestions...)+ meta.Version++++ if err := chunk.SetFAQMetadata(meta); err != nil {+ return nil, err+ }++ // Update chunk content+ 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 nil, err+ }++ // Index new similar questions+ faqKnowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, chunk.KnowledgeID)+ if err != nil {+ return nil, err+ }++ embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)+ if err != nil {+ return nil, err+ }++ questionIndexMode := types.FAQQuestionIndexModeCombined+ if kb.FAQConfig != nil && kb.FAQConfig.QuestionIndexMode != "" {+ questionIndexMode = kb.FAQConfig.QuestionIndexMode+ }++ if questionIndexMode == types.FAQQuestionIndexModeSeparate {+ // Only index the new similar questions+ if err := s.incrementalIndexFAQEntry(ctx, kb, faqKnowledge, chunk, embeddingModel,+ meta.StandardQuestion, oldSimilarQuestions, meta.Answers, meta); err != nil {+ return nil, err+ }+ } else {+ // Combined mode, re-index the whole entry+ if err := s.indexFAQChunks(ctx, kb, faqKnowledge, []*types.Chunk{chunk}, embeddingModel, false, false); err != nil {+ return nil, err+ }+ }++ // Build response+ tagSeqIDMap := make(map[string]int64)+ if chunk.TagID != "" {+ tag, tagErr := s.tagRepo.GetByID(ctx, tenantID, chunk.TagID)+ if tagErr == nil && tag != nil {+ tagSeqIDMap[tag.ID] = tag.SeqID+ }+ }++ entry, err := s.chunkToFAQEntry(chunk, kb, tagSeqIDMap)+ if err != nil {+ return nil, err+ }++ if chunk.TagID != "" {+ tag, tagErr := s.tagRepo.GetByID(ctx, tenantID, chunk.TagID)+ if tagErr == nil && tag != nil {+ entry.TagName = tag.Name+ }+ }++ return entry, nil+}+// UpdateFAQEntryStatus updates enable status for a FAQ entry.func (s *knowledgeService) UpdateFAQEntryStatus(ctx context.Context,kbID string, entryID string, isEnabled bool,diff --git a/internal/handler/faq.go b/internal/handler/faq.goindex 86d066e15..c1a7aa392 100644--- a/internal/handler/faq.go+++ b/internal/handler/faq.go@@ -272,6 +272,11 @@ type faqEntryTagBatchRequest struct {Updates map[int64]*int64 `json:"updates" binding:"required,min=1"`}+// addSimilarQuestionsRequest is a request for adding similar questions to a FAQ entry+type addSimilarQuestionsRequest struct {+ SimilarQuestions []string `json:"similar_questions" binding:"required,min=1"`+}+// DeleteEntries godoc// @Summary 批量删除FAQ条目// @Description 批量删除指定的FAQ条目@@ -484,3 +489,48 @@ func (h *FAQHandler) UpdateLastImportResultDisplayStatus(c *gin.Context) {"success": true,})}++// AddSimilarQuestions godoc+// @Summary 添加相似问+// @Description 向指定的FAQ条目添加相似问题+// @Tags FAQ管理+// @Accept json+// @Produce json+// @Param id path string true "知识库ID"+// @Param entry_id path int true "FAQ条目ID(seq_id)"+// @Param request body addSimilarQuestionsRequest true "相似问列表"+// @Success 200 {object} map[string]interface{} "更新后的FAQ条目"+// @Failure 400 {object} errors.AppError "请求参数错误"+// @Failure 404 {object} errors.AppError "条目不存在"+// @Security Bearer+// @Security ApiKeyAuth+// @Router /knowledge-bases/{id}/faq/entries/{entry_id}/similar-questions [post]+func (h *FAQHandler) AddSimilarQuestions(c *gin.Context) {+ ctx := c.Request.Context()+ kbID := secutils.SanitizeForLog(c.Param("id"))++ entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64)+ if err != nil {+ c.Error(errors.NewBadRequestError("entry_id 必须是整数"))+ return+ }++ var req addSimilarQuestionsRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ logger.Error(ctx, "Failed to bind add similar questions payload", err)+ c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))+ return+ }++ entry, err := h.knowledgeService.AddSimilarQuestions(ctx, kbID, entrySeqID, req.SimilarQuestions)+ if err != nil {+ logger.ErrorWithFields(ctx, err, nil)+ c.Error(err)+ return+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": entry,+ })+}diff --git a/internal/router/router.go b/internal/router/router.goindex f228634bf..e44584b0e 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -189,6 +189,7 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler) {faq.POST("/entries", handler.UpsertEntries)faq.POST("/entry", handler.CreateEntry)faq.PUT("/entries/:entry_id", handler.UpdateEntry)+ faq.POST("/entries/:entry_id/similar-questions", handler.AddSimilarQuestions)// Unified batch update API - supports is_enabled, is_recommended, tag_idfaq.PUT("/entries/fields", handler.UpdateEntryFieldsBatch)faq.PUT("/entries/tags", handler.UpdateEntryTagBatch)diff --git a/internal/types/interfaces/knowledge.go b/internal/types/interfaces/knowledge.goindex cc4ff5857..9bffa6965 100644--- a/internal/types/interfaces/knowledge.go+++ b/internal/types/interfaces/knowledge.go@@ -95,6 +95,8 @@ type KnowledgeService interface {GetFAQEntry(ctx context.Context, kbID string, entrySeqID int64) (*types.FAQEntry, error)// UpdateFAQEntry updates a single FAQ entry.UpdateFAQEntry(ctx context.Context, kbID string, entrySeqID int64, payload *types.FAQEntryPayload) (*types.FAQEntry, error)+ // AddSimilarQuestions adds similar questions to a FAQ entry.+ AddSimilarQuestions(ctx context.Context, kbID string, entrySeqID int64, questions []string) (*types.FAQEntry, error)// UpdateFAQEntryFieldsBatch updates multiple fields for FAQ entries in batch.// Supports updating is_enabled, is_recommended, tag_id, and other fields in a single call.UpdateFAQEntryFieldsBatch(ctx context.Context, kbID string, req *types.FAQEntryFieldsBatchUpdate) error