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:
wizardchen
2026-03-25 20:58:21 +08:00
committed by lyingbug
parent 1416217a0a
commit 1960fc2d90
14 changed files with 763 additions and 4 deletions
+96
View File
@@ -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
}
+192 -3
View File
@@ -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
}