feat(suggested-questions): implement suggested questions feature for chat interface
- Added a new API endpoint to fetch suggested questions based on the agent's associated knowledge bases. - Implemented frontend components to display suggested questions in both chat and create chat views, enhancing user interaction. - Updated localization files to include translations for suggested questions in English, Korean, Russian, and Chinese. - Introduced debounce logic for fetching suggestions to optimize performance during knowledge base changes. - Enhanced backend services to support fetching and returning suggested questions, improving the overall chat experience.
This commit is contained in:
@@ -910,3 +910,99 @@ func (r *chunkRepository) FAQChunkDiff(
|
||||
|
||||
return chunksToAdd, chunksToDelete, nil
|
||||
}
|
||||
|
||||
// ListRecommendedFAQChunks lists FAQ chunks with the recommended flag set.
|
||||
// Filter by kbIDs and/or knowledgeIDs (OR relationship). At least one must be non-empty.
|
||||
// Returns up to `limit` chunks sorted by updated_at descending.
|
||||
func (r *chunkRepository) ListRecommendedFAQChunks(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
kbIDs []string,
|
||||
knowledgeIDs []string,
|
||||
limit int,
|
||||
) ([]*types.Chunk, error) {
|
||||
if limit <= 0 {
|
||||
limit = 10
|
||||
}
|
||||
if len(kbIDs) == 0 && len(knowledgeIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var chunks []*types.Chunk
|
||||
query := r.db.WithContext(ctx).
|
||||
Select("id, knowledge_base_id, chunk_type, metadata, flags, updated_at").
|
||||
Where("tenant_id = ? AND chunk_type = ? AND status IN ? AND is_enabled = ? AND flags & ? != 0",
|
||||
tenantID, types.ChunkTypeFAQ, []int{int(types.ChunkStatusIndexed), int(types.ChunkStatusDefault)}, true, int(types.ChunkFlagRecommended))
|
||||
if len(knowledgeIDs) > 0 {
|
||||
// 指定了具体知识文档,直接按 knowledge_id 过滤(忽略 kbIDs)
|
||||
query = query.Where("knowledge_id IN ?", knowledgeIDs)
|
||||
} else {
|
||||
query = query.Where("knowledge_base_id IN ?", kbIDs)
|
||||
}
|
||||
if err := query.
|
||||
Order("updated_at DESC").
|
||||
Limit(limit).
|
||||
Find(&chunks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
// ListRecentDocumentChunksWithQuestions lists recent document chunks that have generated questions.
|
||||
// Filter by kbIDs and/or knowledgeIDs (OR relationship). At least one must be non-empty.
|
||||
// Returns up to `limit` chunks sorted by updated_at descending.
|
||||
func (r *chunkRepository) ListRecentDocumentChunksWithQuestions(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
kbIDs []string,
|
||||
knowledgeIDs []string,
|
||||
limit int,
|
||||
) ([]*types.Chunk, error) {
|
||||
if limit <= 0 {
|
||||
limit = 10
|
||||
}
|
||||
if len(kbIDs) == 0 && len(knowledgeIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var chunks []*types.Chunk
|
||||
|
||||
baseQuery := r.db.WithContext(ctx).
|
||||
Select("id, knowledge_base_id, chunk_type, metadata, updated_at").
|
||||
Where("tenant_id = ? AND chunk_type = ? AND status IN ? AND is_enabled = ?",
|
||||
tenantID, types.ChunkTypeText, []int{int(types.ChunkStatusIndexed), int(types.ChunkStatusDefault)}, true)
|
||||
if len(knowledgeIDs) > 0 {
|
||||
// 指定了具体知识文档,直接按 knowledge_id 过滤(忽略 kbIDs)
|
||||
baseQuery = baseQuery.Where("knowledge_id IN ?", knowledgeIDs)
|
||||
} else {
|
||||
baseQuery = baseQuery.Where("knowledge_base_id IN ?", kbIDs)
|
||||
}
|
||||
|
||||
// Query chunks that have non-empty generated_questions in metadata
|
||||
switch r.db.Name() {
|
||||
case "postgres":
|
||||
if err := baseQuery.
|
||||
Where("metadata IS NOT NULL AND metadata::text != '{}' AND jsonb_array_length(COALESCE(metadata->'generated_questions', '[]'::jsonb)) > 0").
|
||||
Order("updated_at DESC").
|
||||
Limit(limit).
|
||||
Find(&chunks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "mysql":
|
||||
if err := baseQuery.
|
||||
Where("metadata IS NOT NULL AND JSON_LENGTH(JSON_EXTRACT(metadata, '$.generated_questions')) > 0").
|
||||
Order("updated_at DESC").
|
||||
Limit(limit).
|
||||
Find(&chunks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default: // sqlite
|
||||
if err := baseQuery.
|
||||
Where("metadata IS NOT NULL AND json_array_length(json_extract(metadata, '$.generated_questions')) > 0").
|
||||
Order("updated_at DESC").
|
||||
Limit(limit).
|
||||
Find(&chunks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return chunks, nil
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -23,13 +24,21 @@ var (
|
||||
|
||||
// customAgentService implements the CustomAgentService interface
|
||||
type customAgentService struct {
|
||||
repo interfaces.CustomAgentRepository
|
||||
repo interfaces.CustomAgentRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
}
|
||||
|
||||
// NewCustomAgentService creates a new custom agent service
|
||||
func NewCustomAgentService(repo interfaces.CustomAgentRepository) interfaces.CustomAgentService {
|
||||
func NewCustomAgentService(
|
||||
repo interfaces.CustomAgentRepository,
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
) interfaces.CustomAgentService {
|
||||
return &customAgentService{
|
||||
repo: repo,
|
||||
repo: repo,
|
||||
chunkRepo: chunkRepo,
|
||||
kbService: kbService,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -410,3 +419,183 @@ func (s *customAgentService) CopyAgent(ctx context.Context, id string) (*types.C
|
||||
logger.Infof(ctx, "Agent copied successfully, source ID: %s, new ID: %s", id, newAgent.ID)
|
||||
return newAgent, nil
|
||||
}
|
||||
|
||||
// GetSuggestedQuestions returns suggested questions for the agent based on its
|
||||
// associated knowledge bases.
|
||||
func (s *customAgentService) GetSuggestedQuestions(
|
||||
ctx context.Context,
|
||||
agentID string,
|
||||
kbIDs []string,
|
||||
knowledgeIDs []string,
|
||||
limit int,
|
||||
) ([]types.SuggestedQuestion, error) {
|
||||
if limit <= 0 {
|
||||
limit = 6
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
tenantID, ok := types.TenantIDFromContext(ctx)
|
||||
if !ok {
|
||||
return nil, ErrInvalidTenantID
|
||||
}
|
||||
|
||||
// Get agent configuration
|
||||
agent, err := s.GetAgentByID(ctx, agentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var result []types.SuggestedQuestion
|
||||
|
||||
// 1. Add agent config suggested_prompts first (highest priority)
|
||||
if len(agent.Config.SuggestedPrompts) > 0 {
|
||||
for _, prompt := range agent.Config.SuggestedPrompts {
|
||||
if strings.TrimSpace(prompt) == "" {
|
||||
continue
|
||||
}
|
||||
result = append(result, types.SuggestedQuestion{
|
||||
Question: prompt,
|
||||
Source: "agent_config",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Determine knowledge base scope
|
||||
effectiveKBIDs := kbIDs
|
||||
if len(effectiveKBIDs) == 0 {
|
||||
// Use agent's KB configuration
|
||||
switch agent.Config.KBSelectionMode {
|
||||
case "all":
|
||||
kbs, err := s.kbService.ListKnowledgeBases(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": agentID,
|
||||
})
|
||||
// Return what we have so far (agent_config suggestions)
|
||||
return s.truncateQuestions(result, limit), nil
|
||||
}
|
||||
for _, kb := range kbs {
|
||||
effectiveKBIDs = append(effectiveKBIDs, kb.ID)
|
||||
}
|
||||
case "selected":
|
||||
effectiveKBIDs = agent.Config.KnowledgeBases
|
||||
case "none":
|
||||
// No KB access, return agent_config suggestions only
|
||||
return s.truncateQuestions(result, limit), nil
|
||||
default:
|
||||
// Default to agent's configured KBs
|
||||
effectiveKBIDs = agent.Config.KnowledgeBases
|
||||
}
|
||||
}
|
||||
|
||||
if len(effectiveKBIDs) == 0 && len(knowledgeIDs) == 0 {
|
||||
return s.truncateQuestions(result, limit), nil
|
||||
}
|
||||
|
||||
// Deduplicate questions we've already collected
|
||||
seen := make(map[string]bool)
|
||||
for _, q := range result {
|
||||
seen[q.Question] = true
|
||||
}
|
||||
|
||||
remaining := limit - len(result)
|
||||
if remaining <= 0 {
|
||||
return s.truncateQuestions(result, limit), nil
|
||||
}
|
||||
|
||||
// 3. Collect all candidate chunks from both FAQ and Document KBs,
|
||||
// then sort by updated_at uniformly (not FAQ-first).
|
||||
type candidate struct {
|
||||
question types.SuggestedQuestion
|
||||
updatedAt time.Time
|
||||
}
|
||||
var candidates []candidate
|
||||
|
||||
// Determine query scope
|
||||
queryKBIDs := effectiveKBIDs
|
||||
queryKnowledgeIDs := knowledgeIDs
|
||||
|
||||
// Fetch more than needed from each source, we'll merge-sort and truncate
|
||||
fetchLimit := remaining * 2
|
||||
if fetchLimit < 10 {
|
||||
fetchLimit = 10
|
||||
}
|
||||
|
||||
// Collect FAQ recommended chunks
|
||||
faqChunks, err := s.chunkRepo.ListRecommendedFAQChunks(ctx, tenantID, queryKBIDs, queryKnowledgeIDs, fetchLimit)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": agentID,
|
||||
})
|
||||
} else {
|
||||
for _, chunk := range faqChunks {
|
||||
meta, err := chunk.FAQMetadata()
|
||||
if err != nil || meta == nil || meta.StandardQuestion == "" {
|
||||
continue
|
||||
}
|
||||
if seen[meta.StandardQuestion] {
|
||||
continue
|
||||
}
|
||||
seen[meta.StandardQuestion] = true
|
||||
candidates = append(candidates, candidate{
|
||||
question: types.SuggestedQuestion{
|
||||
Question: meta.StandardQuestion,
|
||||
Source: "faq",
|
||||
KnowledgeBaseID: chunk.KnowledgeBaseID,
|
||||
},
|
||||
updatedAt: chunk.UpdatedAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Collect Document chunks with generated questions
|
||||
docChunks, err := s.chunkRepo.ListRecentDocumentChunksWithQuestions(ctx, tenantID, queryKBIDs, queryKnowledgeIDs, fetchLimit)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": agentID,
|
||||
})
|
||||
} else {
|
||||
for _, chunk := range docChunks {
|
||||
meta, err := chunk.DocumentMetadata()
|
||||
if err != nil || meta == nil || len(meta.GeneratedQuestions) == 0 {
|
||||
continue
|
||||
}
|
||||
q := meta.GeneratedQuestions[0].Question
|
||||
if q == "" || seen[q] {
|
||||
continue
|
||||
}
|
||||
seen[q] = true
|
||||
candidates = append(candidates, candidate{
|
||||
question: types.SuggestedQuestion{
|
||||
Question: q,
|
||||
Source: "document",
|
||||
KnowledgeBaseID: chunk.KnowledgeBaseID,
|
||||
},
|
||||
updatedAt: chunk.UpdatedAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Sort all candidates by updated_at descending (newest first)
|
||||
sort.Slice(candidates, func(i, j int) bool {
|
||||
return candidates[i].updatedAt.After(candidates[j].updatedAt)
|
||||
})
|
||||
|
||||
// 5. Pick top N
|
||||
for _, c := range candidates {
|
||||
if len(result) >= limit {
|
||||
break
|
||||
}
|
||||
result = append(result, c.question)
|
||||
}
|
||||
|
||||
return s.truncateQuestions(result, limit), nil
|
||||
}
|
||||
|
||||
// truncateQuestions truncates the question list to the specified limit
|
||||
func (s *customAgentService) truncateQuestions(questions []types.SuggestedQuestion, limit int) []types.SuggestedQuestion {
|
||||
if len(questions) > limit {
|
||||
return questions[:limit]
|
||||
}
|
||||
return questions
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
@@ -376,3 +378,80 @@ func (h *CustomAgentHandler) GetPlaceholders(c *gin.Context) {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// GetSuggestedQuestions godoc
|
||||
// @Summary 获取推荐问题
|
||||
// @Description 基于智能体关联的知识库,返回推荐问题供用户快捷提问
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "智能体ID"
|
||||
// @Param knowledge_base_ids query string false "知识库ID列表(逗号分隔),覆盖智能体默认配置"
|
||||
// @Param knowledge_ids query string false "知识ID列表(逗号分隔),限定到具体文档"
|
||||
// @Param limit query int false "返回数量上限(默认6)"
|
||||
// @Success 200 {object} map[string]interface{} "推荐问题列表"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 404 {object} errors.AppError "智能体不存在"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents/{id}/suggested-questions [get]
|
||||
func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get agent ID from URL parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Agent ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
// Parse optional query parameters
|
||||
var kbIDs []string
|
||||
if kbIDsStr := strings.TrimSpace(c.Query("knowledge_base_ids")); kbIDsStr != "" {
|
||||
for _, id := range strings.Split(kbIDsStr, ",") {
|
||||
if trimmed := strings.TrimSpace(id); trimmed != "" {
|
||||
kbIDs = append(kbIDs, trimmed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var knowledgeIDs []string
|
||||
if kIDsStr := strings.TrimSpace(c.Query("knowledge_ids")); kIDsStr != "" {
|
||||
for _, id := range strings.Split(kIDsStr, ",") {
|
||||
if trimmed := strings.TrimSpace(id); trimmed != "" {
|
||||
knowledgeIDs = append(knowledgeIDs, trimmed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
limit := 6
|
||||
if limitStr := c.Query("limit"); limitStr != "" {
|
||||
if parsed, err := strconv.Atoi(limitStr); err == nil && parsed > 0 {
|
||||
limit = parsed
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Getting suggested questions for agent %s, kbIDs: %v, limit: %d",
|
||||
secutils.SanitizeForLog(id), kbIDs, limit)
|
||||
|
||||
questions, err := h.service.GetSuggestedQuestions(ctx, id, kbIDs, knowledgeIDs, limit)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
})
|
||||
if err == service.ErrAgentNotFound {
|
||||
c.Error(errors.NewNotFoundError("Agent not found"))
|
||||
return
|
||||
}
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"questions": questions,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -491,6 +491,8 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomA
|
||||
// Copy agent
|
||||
agents.POST("/:id/copy", agentHandler.CopyAgent)
|
||||
}
|
||||
// Registered outside the group to avoid Gin route conflict with /agents/:id/shares in organization routes
|
||||
r.GET("/agents/:id/suggested-questions", agentHandler.GetSuggestedQuestions)
|
||||
}
|
||||
|
||||
// RegisterSkillRoutes registers skill routes
|
||||
|
||||
@@ -175,6 +175,10 @@ type CustomAgentConfig struct {
|
||||
FallbackResponse string `yaml:"fallback_response" json:"fallback_response"`
|
||||
// Fallback prompt (when FallbackStrategy is "model")
|
||||
FallbackPrompt string `yaml:"fallback_prompt" json:"fallback_prompt"`
|
||||
|
||||
// ===== Suggested Prompts =====
|
||||
// 推荐问题列表,用于在前端对话面板展示快捷提问
|
||||
SuggestedPrompts []string `yaml:"suggested_prompts" json:"suggested_prompts,omitempty"`
|
||||
}
|
||||
|
||||
// Value implements driver.Valuer interface for CustomAgentConfig
|
||||
@@ -255,6 +259,16 @@ func (a *CustomAgent) IsAgentMode() bool {
|
||||
return a.Config.AgentMode == AgentModeSmartReasoning
|
||||
}
|
||||
|
||||
// SuggestedQuestion 推荐问题
|
||||
type SuggestedQuestion struct {
|
||||
// 问题文本
|
||||
Question string `json:"question"`
|
||||
// 来源类型: "faq", "document", "agent_config"
|
||||
Source string `json:"source"`
|
||||
// 来源知识库ID(仅 faq/document 来源时有值)
|
||||
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
|
||||
}
|
||||
|
||||
// BuiltinAgentRegistry provides a registry of all built-in agents.
|
||||
// It is initialised empty and populated by LoadBuiltinAgentsConfig from
|
||||
// config/builtin_agents.yaml at startup via rebuildRegistryFromConfig.
|
||||
|
||||
@@ -89,6 +89,16 @@ type ChunkRepository interface {
|
||||
// FAQChunkDiff compares FAQ chunks between two knowledge bases and returns the differences.
|
||||
// Returns: chunksToAdd (content_hash in src but not in dst), chunksToDelete (content_hash in dst but not in src)
|
||||
FAQChunkDiff(ctx context.Context, srcTenantID uint64, srcKBID string, dstTenantID uint64, dstKBID string) (chunksToAdd []string, chunksToDelete []string, err error)
|
||||
|
||||
// ListRecommendedFAQChunks lists FAQ chunks with the recommended flag set.
|
||||
// Filter by kbIDs and/or knowledgeIDs. At least one of them must be non-empty.
|
||||
// Returns up to `limit` chunks sorted by updated_at descending.
|
||||
ListRecommendedFAQChunks(ctx context.Context, tenantID uint64, kbIDs []string, knowledgeIDs []string, limit int) ([]*types.Chunk, error)
|
||||
|
||||
// ListRecentDocumentChunksWithQuestions lists recent document chunks that have generated questions.
|
||||
// Filter by kbIDs and/or knowledgeIDs. At least one of them must be non-empty.
|
||||
// Returns up to `limit` chunks sorted by updated_at descending.
|
||||
ListRecentDocumentChunksWithQuestions(ctx context.Context, tenantID uint64, kbIDs []string, knowledgeIDs []string, limit int) ([]*types.Chunk, error)
|
||||
}
|
||||
|
||||
// ChunkService defines the interface for chunk service operations
|
||||
|
||||
@@ -64,6 +64,20 @@ type CustomAgentService interface {
|
||||
// - The newly created agent copy
|
||||
// - Possible errors such as not existing, insufficient permissions, etc.
|
||||
CopyAgent(ctx context.Context, id string) (*types.CustomAgent, error)
|
||||
|
||||
// GetSuggestedQuestions returns suggested questions for the agent based on its
|
||||
// associated knowledge bases. When kbIDs or knowledgeIDs are provided, they override
|
||||
// the agent's default knowledge base selection.
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - agentID: Agent ID
|
||||
// - kbIDs: Optional knowledge base IDs to override agent config
|
||||
// - knowledgeIDs: Optional knowledge item IDs to further filter
|
||||
// - limit: Maximum number of questions to return
|
||||
// Returns:
|
||||
// - List of suggested questions
|
||||
// - Possible errors
|
||||
GetSuggestedQuestions(ctx context.Context, agentID string, kbIDs []string, knowledgeIDs []string, limit int) ([]types.SuggestedQuestion, error)
|
||||
}
|
||||
|
||||
// CustomAgentRepository defines the custom agent repository interface
|
||||
|
||||
Reference in New Issue
Block a user