feat(agent): add question suggestions with after-answer follow-ups
Enable agents to configure starter prompts and async follow-up questions after completed answers, with durable caching, analytics events, and chat/embed UI integration.
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type messageSuggestionRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewMessageSuggestionRepository(db *gorm.DB) interfaces.MessageSuggestionRepository {
|
||||
return &messageSuggestionRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) GetByCacheKey(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
assistantMessageID string,
|
||||
placement string,
|
||||
configHash string,
|
||||
locale string,
|
||||
) (*types.MessageSuggestionSet, error) {
|
||||
var set types.MessageSuggestionSet
|
||||
err := r.db.WithContext(ctx).
|
||||
Where(
|
||||
"tenant_id = ? AND assistant_message_id = ? AND placement = ? AND config_hash = ? AND locale = ?",
|
||||
tenantID, assistantMessageID, placement, configHash, locale,
|
||||
).
|
||||
First(&set).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &set, nil
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) GetByID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
sessionID string,
|
||||
id string,
|
||||
) (*types.MessageSuggestionSet, error) {
|
||||
var set types.MessageSuggestionSet
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("id = ? AND tenant_id = ? AND session_id = ?", id, tenantID, sessionID).
|
||||
First(&set).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &set, nil
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) AcquireGeneration(
|
||||
ctx context.Context,
|
||||
candidate *types.MessageSuggestionSet,
|
||||
regenerate bool,
|
||||
) (*types.MessageSuggestionSet, bool, error) {
|
||||
now := time.Now()
|
||||
leaseUntil := now.Add(3 * time.Minute)
|
||||
candidate.Status = types.SuggestionStatusGenerating
|
||||
candidate.LeaseUntil = &leaseUntil
|
||||
candidate.Questions = types.SuggestionItems{}
|
||||
|
||||
result := r.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(candidate)
|
||||
if result.Error != nil {
|
||||
return nil, false, result.Error
|
||||
}
|
||||
if result.RowsAffected == 1 {
|
||||
return candidate, true, nil
|
||||
}
|
||||
|
||||
existing, err := r.GetByCacheKey(
|
||||
ctx,
|
||||
candidate.TenantID,
|
||||
candidate.AssistantMessageID,
|
||||
candidate.Placement,
|
||||
candidate.ConfigHash,
|
||||
candidate.Locale,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if existing.Status == types.SuggestionStatusReady && !regenerate {
|
||||
return existing, false, nil
|
||||
}
|
||||
if existing.Status == types.SuggestionStatusSuppressed && !regenerate {
|
||||
return existing, false, nil
|
||||
}
|
||||
if existing.Status == types.SuggestionStatusGenerating && existing.LeaseUntil != nil && existing.LeaseUntil.After(now) {
|
||||
return existing, false, nil
|
||||
}
|
||||
|
||||
query := r.db.WithContext(ctx).Model(&types.MessageSuggestionSet{}).
|
||||
Where("id = ?", existing.ID).
|
||||
Where("status <> ? OR lease_until IS NULL OR lease_until < ?", types.SuggestionStatusGenerating, now)
|
||||
if existing.Status == types.SuggestionStatusReady && regenerate {
|
||||
query = r.db.WithContext(ctx).Model(&types.MessageSuggestionSet{}).
|
||||
Where("id = ? AND status = ?", existing.ID, types.SuggestionStatusReady)
|
||||
}
|
||||
updates := map[string]interface{}{
|
||||
"status": types.SuggestionStatusGenerating,
|
||||
"lease_until": leaseUntil,
|
||||
"suppression_reason": "",
|
||||
"questions": types.SuggestionItems{},
|
||||
"error_code": "",
|
||||
"generated_at": nil,
|
||||
"updated_at": now,
|
||||
}
|
||||
result = query.Updates(updates)
|
||||
if result.Error != nil {
|
||||
return nil, false, result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
current, getErr := r.GetByCacheKey(
|
||||
ctx,
|
||||
candidate.TenantID,
|
||||
candidate.AssistantMessageID,
|
||||
candidate.Placement,
|
||||
candidate.ConfigHash,
|
||||
candidate.Locale,
|
||||
)
|
||||
return current, false, getErr
|
||||
}
|
||||
existing.Status = types.SuggestionStatusGenerating
|
||||
existing.LeaseUntil = &leaseUntil
|
||||
existing.Questions = types.SuggestionItems{}
|
||||
return existing, true, nil
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) Save(ctx context.Context, set *types.MessageSuggestionSet) error {
|
||||
if set == nil {
|
||||
return errors.New("message suggestion set is nil")
|
||||
}
|
||||
return r.db.WithContext(ctx).Save(set).Error
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) CreateEvent(
|
||||
ctx context.Context,
|
||||
event *types.MessageSuggestionEvent,
|
||||
) error {
|
||||
return r.db.WithContext(ctx).Create(event).Error
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) DeleteByMessageID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
sessionID string,
|
||||
messageID string,
|
||||
) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND session_id = ? AND assistant_message_id = ?", tenantID, sessionID, messageID).
|
||||
Delete(&types.MessageSuggestionSet{}).Error
|
||||
}
|
||||
|
||||
func (r *messageSuggestionRepository) DeleteBySessionID(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
sessionID string,
|
||||
) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND session_id = ?", tenantID, sessionID).
|
||||
Delete(&types.MessageSuggestionSet{}).Error
|
||||
}
|
||||
@@ -34,8 +34,9 @@ func scopeCustomAgentsByModelID(db *gorm.DB, modelID string) *gorm.DB {
|
||||
return db.Where(
|
||||
"config->>'model_id' = ? OR config->>'rerank_model_id' = ? OR "+
|
||||
"config->>'vlm_model_id' = ? OR config->>'asr_model_id' = ? OR "+
|
||||
"config->>'query_understand_model_id' = ?",
|
||||
modelID, modelID, modelID, modelID, modelID,
|
||||
"config->>'query_understand_model_id' = ? OR "+
|
||||
"config->'question_suggestions'->'follow_ups'->>'model_id' = ?",
|
||||
modelID, modelID, modelID, modelID, modelID, modelID,
|
||||
)
|
||||
}
|
||||
return db.Where(
|
||||
@@ -43,7 +44,8 @@ func scopeCustomAgentsByModelID(db *gorm.DB, modelID string) *gorm.DB {
|
||||
"json_extract(config, '$.rerank_model_id') = ? OR "+
|
||||
"json_extract(config, '$.vlm_model_id') = ? OR "+
|
||||
"json_extract(config, '$.asr_model_id') = ? OR "+
|
||||
"json_extract(config, '$.query_understand_model_id') = ?",
|
||||
modelID, modelID, modelID, modelID, modelID,
|
||||
"json_extract(config, '$.query_understand_model_id') = ? OR "+
|
||||
"json_extract(config, '$.question_suggestions.follow_ups.model_id') = ?",
|
||||
modelID, modelID, modelID, modelID, modelID, modelID,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -97,6 +97,9 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo
|
||||
|
||||
// Set defaults
|
||||
agent.EnsureDefaults()
|
||||
if err := agent.Config.QuestionSuggestions.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Creating custom agent, ID: %s, tenant ID: %d, name: %s, agent_mode: %s",
|
||||
agent.ID, agent.TenantID, agent.Name, agent.Config.AgentMode)
|
||||
@@ -132,6 +135,7 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*type
|
||||
agent, err := s.repo.GetAgentByID(ctx, id, tenantID)
|
||||
if err == nil {
|
||||
// Found in database, return with customized config
|
||||
agent.EnsureDefaults()
|
||||
return agent, nil
|
||||
}
|
||||
// Not in database, return default built-in agent from registry (i18n-aware)
|
||||
@@ -152,6 +156,7 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*type
|
||||
return nil, err
|
||||
}
|
||||
|
||||
agent.EnsureDefaults()
|
||||
return agent, nil
|
||||
}
|
||||
|
||||
@@ -168,6 +173,7 @@ func (s *customAgentService) GetAgentByIDAndTenant(ctx context.Context, id strin
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
agent.EnsureDefaults()
|
||||
return agent, nil
|
||||
}
|
||||
|
||||
@@ -190,6 +196,7 @@ func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAge
|
||||
// Track which built-in agents exist in database
|
||||
builtinInDB := make(map[string]bool)
|
||||
for _, agent := range allAgents {
|
||||
agent.EnsureDefaults()
|
||||
if types.IsBuiltinAgentID(agent.ID) {
|
||||
builtinInDB[agent.ID] = true
|
||||
}
|
||||
@@ -273,6 +280,9 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo
|
||||
|
||||
// Ensure defaults
|
||||
existingAgent.EnsureDefaults()
|
||||
if err := existingAgent.Config.QuestionSuggestions.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Updating custom agent, ID: %s, name: %s", agent.ID, agent.Name)
|
||||
|
||||
@@ -306,6 +316,9 @@ func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *type
|
||||
existingAgent.Config = agent.Config
|
||||
existingAgent.UpdatedAt = time.Now()
|
||||
existingAgent.EnsureDefaults()
|
||||
if err := existingAgent.Config.QuestionSuggestions.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Updating built-in agent config, ID: %s", agent.ID)
|
||||
|
||||
@@ -333,6 +346,9 @@ func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *type
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
newAgent.EnsureDefaults()
|
||||
if err := newAgent.Config.QuestionSuggestions.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Creating built-in agent config record, ID: %s, tenant ID: %d", agent.ID, tenantID)
|
||||
|
||||
@@ -457,6 +473,29 @@ func (s *customAgentService) GetSuggestedQuestions(
|
||||
knowledgeIDs []string,
|
||||
tagIDs []string,
|
||||
limit int,
|
||||
) ([]types.SuggestedQuestion, error) {
|
||||
return s.getSuggestedQuestions(ctx, agentID, kbIDs, knowledgeIDs, tagIDs, limit, true)
|
||||
}
|
||||
|
||||
func (s *customAgentService) GetKnowledgeSuggestedQuestions(
|
||||
ctx context.Context,
|
||||
agentID string,
|
||||
kbIDs []string,
|
||||
knowledgeIDs []string,
|
||||
tagIDs []string,
|
||||
limit int,
|
||||
) ([]types.SuggestedQuestion, error) {
|
||||
return s.getSuggestedQuestions(ctx, agentID, kbIDs, knowledgeIDs, tagIDs, limit, false)
|
||||
}
|
||||
|
||||
func (s *customAgentService) getSuggestedQuestions(
|
||||
ctx context.Context,
|
||||
agentID string,
|
||||
kbIDs []string,
|
||||
knowledgeIDs []string,
|
||||
tagIDs []string,
|
||||
limit int,
|
||||
includeCurated bool,
|
||||
) ([]types.SuggestedQuestion, error) {
|
||||
if limit <= 0 {
|
||||
limit = 6
|
||||
@@ -483,16 +522,29 @@ func (s *customAgentService) GetSuggestedQuestions(
|
||||
|
||||
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
|
||||
if includeCurated {
|
||||
suggestionConfig := agent.Config.QuestionSuggestions
|
||||
if suggestionConfig == nil || !suggestionConfig.Starters.Enabled {
|
||||
return []types.SuggestedQuestion{}, nil
|
||||
}
|
||||
if limit > suggestionConfig.Starters.Count {
|
||||
limit = suggestionConfig.Starters.Count
|
||||
}
|
||||
// Add curated agent prompts first (highest priority).
|
||||
if suggestionConfig.Starters.Mode == types.SuggestionModeCurated ||
|
||||
suggestionConfig.Starters.Mode == types.SuggestionModeHybrid {
|
||||
for _, prompt := range suggestionConfig.Starters.Items {
|
||||
if strings.TrimSpace(prompt) == "" {
|
||||
continue
|
||||
}
|
||||
result = append(result, types.SuggestedQuestion{
|
||||
Question: prompt,
|
||||
Source: "agent_config",
|
||||
})
|
||||
}
|
||||
result = append(result, types.SuggestedQuestion{
|
||||
Question: prompt,
|
||||
Source: "agent_config",
|
||||
})
|
||||
}
|
||||
if suggestionConfig.Starters.Mode == types.SuggestionModeCurated {
|
||||
return s.truncateQuestions(result, limit), nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,12 +22,13 @@ var regThinkIndex = regexp.MustCompile(`(?s)<think>.*?</think>`)
|
||||
// It reads the chat history knowledge base configuration from the tenant's ChatHistoryConfig,
|
||||
// which is managed via the settings UI.
|
||||
type messageService struct {
|
||||
messageRepo interfaces.MessageRepository // Repository for message storage operations
|
||||
sessionRepo interfaces.SessionRepository // Repository for session validation
|
||||
tenantService interfaces.TenantService // Service for tenant operations (read ChatHistoryConfig)
|
||||
kbService interfaces.KnowledgeBaseService // Service for knowledge base operations (search chat history KB)
|
||||
knowService interfaces.KnowledgeService // Service for knowledge operations (index/delete passages)
|
||||
modelService interfaces.ModelService // Service for model operations (rerank model)
|
||||
messageRepo interfaces.MessageRepository // Repository for message storage operations
|
||||
sessionRepo interfaces.SessionRepository // Repository for session validation
|
||||
tenantService interfaces.TenantService // Service for tenant operations (read ChatHistoryConfig)
|
||||
kbService interfaces.KnowledgeBaseService // Service for knowledge base operations (search chat history KB)
|
||||
knowService interfaces.KnowledgeService // Service for knowledge operations (index/delete passages)
|
||||
modelService interfaces.ModelService // Service for model operations (rerank model)
|
||||
suggestionRepo interfaces.MessageSuggestionRepository
|
||||
}
|
||||
|
||||
// NewMessageService creates a new message service instance with the required repositories
|
||||
@@ -37,14 +38,16 @@ func NewMessageService(messageRepo interfaces.MessageRepository,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
knowService interfaces.KnowledgeService,
|
||||
modelService interfaces.ModelService,
|
||||
suggestionRepo interfaces.MessageSuggestionRepository,
|
||||
) interfaces.MessageService {
|
||||
return &messageService{
|
||||
messageRepo: messageRepo,
|
||||
sessionRepo: sessionRepo,
|
||||
tenantService: tenantService,
|
||||
kbService: kbService,
|
||||
knowService: knowService,
|
||||
modelService: modelService,
|
||||
messageRepo: messageRepo,
|
||||
sessionRepo: sessionRepo,
|
||||
tenantService: tenantService,
|
||||
kbService: kbService,
|
||||
knowService: knowService,
|
||||
modelService: modelService,
|
||||
suggestionRepo: suggestionRepo,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,6 +292,11 @@ func (s *messageService) DeleteMessage(ctx context.Context, sessionID string, me
|
||||
})
|
||||
return err
|
||||
}
|
||||
if s.suggestionRepo != nil {
|
||||
if err := s.suggestionRepo.DeleteByMessageID(ctx, tenantID, sessionID, messageID); err != nil {
|
||||
logger.Warnf(ctx, "Failed to delete suggestions for message %s: %v", messageID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Async cleanup: delete the associated Knowledge entry from the chat history KB.
|
||||
// Use WithoutCancel so the goroutine survives after the HTTP request context is done.
|
||||
@@ -319,6 +327,11 @@ func (s *messageService) ClearSessionMessages(ctx context.Context, sessionID str
|
||||
logger.Errorf(ctx, "Failed to delete messages for session %s: %v", sessionID, err)
|
||||
return err
|
||||
}
|
||||
if s.suggestionRepo != nil {
|
||||
if err := s.suggestionRepo.DeleteBySessionID(ctx, tenantID, sessionID); err != nil {
|
||||
logger.Warnf(ctx, "Failed to delete suggestions for session %s: %v", sessionID, err)
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "All messages cleared for session: %s", sessionID)
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,567 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var suggestionThinkBlock = regexp.MustCompile(`(?s)<think>.*?</think>`)
|
||||
var trailingCitationTags = regexp.MustCompile(`(?s)(?:\s*<(?:kb|web)>.*?</(?:kb|web)>)+\s*$`)
|
||||
|
||||
type messageSuggestionService struct {
|
||||
repo interfaces.MessageSuggestionRepository
|
||||
messageService interfaces.MessageService
|
||||
modelService interfaces.ModelService
|
||||
customAgentService interfaces.CustomAgentService
|
||||
}
|
||||
|
||||
func NewMessageSuggestionService(
|
||||
repo interfaces.MessageSuggestionRepository,
|
||||
messageService interfaces.MessageService,
|
||||
modelService interfaces.ModelService,
|
||||
customAgentService interfaces.CustomAgentService,
|
||||
) interfaces.MessageSuggestionService {
|
||||
return &messageSuggestionService{
|
||||
repo: repo,
|
||||
messageService: messageService,
|
||||
modelService: modelService,
|
||||
customAgentService: customAgentService,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *messageSuggestionService) EnsureFollowUps(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
assistantMessageID string,
|
||||
regenerate bool,
|
||||
) (*types.MessageSuggestionSet, error) {
|
||||
message, err := s.messageService.GetMessage(ctx, sessionID, assistantMessageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if message.Role != "assistant" || !message.IsCompleted {
|
||||
return nil, errors.New("follow-up suggestions require a completed assistant message")
|
||||
}
|
||||
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
locale := message.ExecutionContext.Locale
|
||||
if locale == "" {
|
||||
locale, _ = types.LanguageFromContext(ctx)
|
||||
}
|
||||
if locale == "" {
|
||||
locale = types.DefaultLanguage()
|
||||
}
|
||||
configHash := message.ExecutionContext.AgentConfigHash
|
||||
if configHash == "" {
|
||||
configHash = "no-agent-config"
|
||||
}
|
||||
config := message.ExecutionContext.QuestionSuggestions
|
||||
if regenerate && (config == nil || !config.FollowUps.Enabled || !config.FollowUps.AllowRegenerate) {
|
||||
return nil, errors.New("suggestion regeneration is not allowed")
|
||||
}
|
||||
candidate := &types.MessageSuggestionSet{
|
||||
TenantID: tenantID,
|
||||
SessionID: sessionID,
|
||||
AssistantMessageID: assistantMessageID,
|
||||
AgentID: message.AgentID,
|
||||
AgentTenantID: message.AgentTenantID,
|
||||
Placement: types.SuggestionPlacementAfterAnswer,
|
||||
ConfigHash: configHash,
|
||||
Locale: locale,
|
||||
AllowRegenerate: config != nil && config.FollowUps.AllowRegenerate,
|
||||
}
|
||||
set, acquired, err := s.repo.AcquireGeneration(ctx, candidate, regenerate)
|
||||
if err != nil || !acquired {
|
||||
return set, err
|
||||
}
|
||||
|
||||
if config == nil || !config.FollowUps.Enabled {
|
||||
return s.suppress(ctx, set, "disabled")
|
||||
}
|
||||
if message.IsFallback && config.FollowUps.SuppressOnFallback {
|
||||
return s.suppress(ctx, set, "fallback_answer")
|
||||
}
|
||||
answer := strings.TrimSpace(suggestionThinkBlock.ReplaceAllString(message.Content, ""))
|
||||
if answer == "" {
|
||||
return s.suppress(ctx, set, "empty_answer")
|
||||
}
|
||||
if config.FollowUps.SuppressWhenAnswerAsksQuestion && answerEndsWithQuestion(answer) {
|
||||
return s.suppress(ctx, set, "answer_asks_question")
|
||||
}
|
||||
|
||||
startedAt := time.Now()
|
||||
set.ModelID = config.FollowUps.ModelID
|
||||
if set.ModelID == "" {
|
||||
set.ModelID = message.ModelID
|
||||
}
|
||||
questions, usage, generateErr := s.generate(
|
||||
ctx,
|
||||
message,
|
||||
answer,
|
||||
config.FollowUps,
|
||||
)
|
||||
set.LatencyMs = time.Since(startedAt).Milliseconds()
|
||||
set.PromptTokens = usage.PromptTokens
|
||||
set.CompletionTokens = usage.CompletionTokens
|
||||
set.LeaseUntil = nil
|
||||
generatedAt := time.Now()
|
||||
set.GeneratedAt = &generatedAt
|
||||
|
||||
if generateErr != nil {
|
||||
set.Status = types.SuggestionStatusFailed
|
||||
set.ErrorCode = suggestionErrorCode(generateErr)
|
||||
if saveErr := s.repo.Save(ctx, set); saveErr != nil {
|
||||
return nil, saveErr
|
||||
}
|
||||
logger.ErrorWithFields(ctx, generateErr, map[string]interface{}{
|
||||
"session_id": sessionID,
|
||||
"message_id": assistantMessageID,
|
||||
"set_id": set.ID,
|
||||
})
|
||||
return set, nil
|
||||
}
|
||||
if len(questions) == 0 {
|
||||
return s.suppress(ctx, set, "no_candidates")
|
||||
}
|
||||
set.Questions = questions
|
||||
set.Status = types.SuggestionStatusReady
|
||||
set.ErrorCode = ""
|
||||
if err := s.repo.Save(ctx, set); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if regenerate {
|
||||
_ = s.createEvent(ctx, set, "", types.SuggestionEventRegenerate)
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
|
||||
func (s *messageSuggestionService) GetFollowUps(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
assistantMessageID string,
|
||||
) (*types.MessageSuggestionSet, error) {
|
||||
message, err := s.messageService.GetMessage(ctx, sessionID, assistantMessageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
locale := message.ExecutionContext.Locale
|
||||
if locale == "" {
|
||||
locale, _ = types.LanguageFromContext(ctx)
|
||||
}
|
||||
if locale == "" {
|
||||
locale = types.DefaultLanguage()
|
||||
}
|
||||
configHash := message.ExecutionContext.AgentConfigHash
|
||||
if configHash == "" {
|
||||
configHash = "no-agent-config"
|
||||
}
|
||||
return s.repo.GetByCacheKey(
|
||||
ctx,
|
||||
tenantID,
|
||||
assistantMessageID,
|
||||
types.SuggestionPlacementAfterAnswer,
|
||||
configHash,
|
||||
locale,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *messageSuggestionService) RecordEvent(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
setID string,
|
||||
questionID string,
|
||||
eventType string,
|
||||
) error {
|
||||
if eventType != types.SuggestionEventImpression &&
|
||||
eventType != types.SuggestionEventClick &&
|
||||
eventType != types.SuggestionEventDismiss {
|
||||
return errors.New("invalid suggestion event type")
|
||||
}
|
||||
tenantID := types.MustTenantIDFromContext(ctx)
|
||||
set, err := s.repo.GetByID(ctx, tenantID, sessionID, setID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if questionID != "" && !containsSuggestionID(set.Questions, questionID) {
|
||||
return errors.New("question does not belong to suggestion set")
|
||||
}
|
||||
if eventType == types.SuggestionEventClick && questionID == "" {
|
||||
return errors.New("click event requires question_id")
|
||||
}
|
||||
return s.createEvent(ctx, set, questionID, eventType)
|
||||
}
|
||||
|
||||
func (s *messageSuggestionService) ValidateAttribution(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
query string,
|
||||
attribution *types.SuggestionAttribution,
|
||||
) error {
|
||||
if attribution == nil {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(attribution.SuggestionSetID) == "" || strings.TrimSpace(attribution.QuestionID) == "" {
|
||||
return errors.New("invalid suggestion attribution")
|
||||
}
|
||||
set, err := s.repo.GetByID(
|
||||
ctx,
|
||||
types.MustTenantIDFromContext(ctx),
|
||||
sessionID,
|
||||
attribution.SuggestionSetID,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if set.Status != types.SuggestionStatusReady {
|
||||
return errors.New("invalid suggestion attribution")
|
||||
}
|
||||
found := false
|
||||
for _, question := range set.Questions {
|
||||
if question.ID == attribution.QuestionID && strings.TrimSpace(question.Text) == strings.TrimSpace(query) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return errors.New("invalid suggestion attribution")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *messageSuggestionService) generate(
|
||||
ctx context.Context,
|
||||
message *types.Message,
|
||||
answer string,
|
||||
config types.FollowUpSuggestionConfig,
|
||||
) (types.SuggestionItems, types.TokenUsage, error) {
|
||||
count := config.Count
|
||||
if count < 1 {
|
||||
count = 3
|
||||
}
|
||||
var generated types.SuggestionItems
|
||||
var usage types.TokenUsage
|
||||
var modelErr error
|
||||
if config.Mode == types.SuggestionModeGenerated || config.Mode == types.SuggestionModeHybrid {
|
||||
generated, usage, modelErr = s.generateWithModel(ctx, message, answer, config, count)
|
||||
}
|
||||
|
||||
needKnowledge := config.Mode == types.SuggestionModeKnowledge ||
|
||||
(config.Mode == types.SuggestionModeHybrid && len(generated) < count) ||
|
||||
(modelErr != nil && config.KnowledgeFallback)
|
||||
if needKnowledge {
|
||||
knowledge, err := s.generateFromKnowledge(ctx, message, count-len(generated))
|
||||
if err != nil && modelErr == nil {
|
||||
modelErr = err
|
||||
}
|
||||
generated = mergeSuggestionItems(generated, knowledge, count)
|
||||
}
|
||||
if len(generated) > 0 {
|
||||
return generated, usage, nil
|
||||
}
|
||||
if modelErr != nil {
|
||||
return nil, usage, modelErr
|
||||
}
|
||||
return generated, usage, nil
|
||||
}
|
||||
|
||||
func (s *messageSuggestionService) generateWithModel(
|
||||
ctx context.Context,
|
||||
message *types.Message,
|
||||
answer string,
|
||||
config types.FollowUpSuggestionConfig,
|
||||
count int,
|
||||
) (types.SuggestionItems, types.TokenUsage, error) {
|
||||
modelID := config.ModelID
|
||||
if modelID == "" {
|
||||
modelID = message.ModelID
|
||||
}
|
||||
if modelID == "" {
|
||||
return nil, types.TokenUsage{}, errors.New("suggestion model is not configured")
|
||||
}
|
||||
|
||||
modelCtx := ctx
|
||||
if message.AgentTenantID != 0 {
|
||||
modelCtx = context.WithValue(modelCtx, types.TenantIDContextKey, message.AgentTenantID)
|
||||
}
|
||||
chatModel, err := s.modelService.GetChatModel(modelCtx, modelID)
|
||||
if err != nil {
|
||||
return nil, types.TokenUsage{}, err
|
||||
}
|
||||
history, err := s.buildHistory(ctx, message.SessionID, config.MaxContextTurns)
|
||||
if err != nil {
|
||||
return nil, types.TokenUsage{}, err
|
||||
}
|
||||
categories := strings.Join(config.Categories, ", ")
|
||||
if categories == "" {
|
||||
categories = "clarify, deepen, action"
|
||||
}
|
||||
language := types.LanguageLocaleName(message.ExecutionContext.Locale)
|
||||
systemPrompt := fmt.Sprintf(
|
||||
"You generate exactly %d short follow-up questions after an assistant answer. "+
|
||||
"Return JSON only as {\"questions\":[{\"text\":\"...\",\"category\":\"...\"}]}. "+
|
||||
"Use %s. Allowed categories: %s. Questions must be answerable from the conversation, "+
|
||||
"must not repeat prior user questions, must not claim unavailable capabilities, and must not include numbering.",
|
||||
count, language, categories,
|
||||
)
|
||||
if instruction := strings.TrimSpace(config.AdditionalInstruction); instruction != "" {
|
||||
systemPrompt += " Additional agent instruction: " + instruction
|
||||
}
|
||||
userPrompt := "Conversation:\n" + history + "\n\nLatest assistant answer:\n" + truncateRunes(answer, 6000)
|
||||
thinking := false
|
||||
response, err := chatModel.Chat(modelCtx, []chat.Message{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
{Role: "user", Content: userPrompt},
|
||||
}, &chat.ChatOptions{
|
||||
Temperature: 0.3,
|
||||
MaxCompletionTokens: 700,
|
||||
Thinking: &thinking,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, types.TokenUsage{}, err
|
||||
}
|
||||
items, err := parseGeneratedSuggestions(response.Content, config.Categories, count)
|
||||
return items, response.Usage, err
|
||||
}
|
||||
|
||||
func (s *messageSuggestionService) generateFromKnowledge(
|
||||
ctx context.Context,
|
||||
message *types.Message,
|
||||
count int,
|
||||
) (types.SuggestionItems, error) {
|
||||
if count <= 0 || message.AgentID == "" {
|
||||
return types.SuggestionItems{}, nil
|
||||
}
|
||||
knowledgeCtx := ctx
|
||||
if message.AgentTenantID != 0 {
|
||||
knowledgeCtx = context.WithValue(knowledgeCtx, types.TenantIDContextKey, message.AgentTenantID)
|
||||
}
|
||||
candidates, err := s.customAgentService.GetKnowledgeSuggestedQuestions(
|
||||
knowledgeCtx,
|
||||
message.AgentID,
|
||||
message.ExecutionContext.KnowledgeBaseIDs,
|
||||
message.ExecutionContext.KnowledgeIDs,
|
||||
message.ExecutionContext.TagIDs,
|
||||
count,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make(types.SuggestionItems, 0, len(candidates))
|
||||
for _, candidate := range candidates {
|
||||
text := strings.TrimSpace(candidate.Question)
|
||||
if text == "" {
|
||||
continue
|
||||
}
|
||||
item := types.SuggestionItem{
|
||||
ID: uuid.NewString(),
|
||||
Text: text,
|
||||
Source: candidate.Source,
|
||||
}
|
||||
if candidate.KnowledgeBaseID != "" {
|
||||
item.KnowledgeBaseIDs = []string{candidate.KnowledgeBaseID}
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (s *messageSuggestionService) buildHistory(ctx context.Context, sessionID string, maxTurns int) (string, error) {
|
||||
if maxTurns < 1 {
|
||||
maxTurns = 2
|
||||
}
|
||||
messages, err := s.messageService.GetRecentMessagesBySession(ctx, sessionID, maxTurns*2+4)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
start := 0
|
||||
if len(messages) > maxTurns*2 {
|
||||
start = len(messages) - maxTurns*2
|
||||
}
|
||||
var builder strings.Builder
|
||||
for _, message := range messages[start:] {
|
||||
content := strings.TrimSpace(suggestionThinkBlock.ReplaceAllString(message.Content, ""))
|
||||
if content == "" {
|
||||
continue
|
||||
}
|
||||
builder.WriteString(message.Role)
|
||||
builder.WriteString(": ")
|
||||
builder.WriteString(truncateRunes(content, 3000))
|
||||
builder.WriteByte('\n')
|
||||
}
|
||||
return builder.String(), nil
|
||||
}
|
||||
|
||||
func (s *messageSuggestionService) suppress(
|
||||
ctx context.Context,
|
||||
set *types.MessageSuggestionSet,
|
||||
reason string,
|
||||
) (*types.MessageSuggestionSet, error) {
|
||||
set.Status = types.SuggestionStatusSuppressed
|
||||
set.SuppressionReason = reason
|
||||
set.Questions = types.SuggestionItems{}
|
||||
set.LeaseUntil = nil
|
||||
now := time.Now()
|
||||
set.GeneratedAt = &now
|
||||
if err := s.repo.Save(ctx, set); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
|
||||
func (s *messageSuggestionService) createEvent(
|
||||
ctx context.Context,
|
||||
set *types.MessageSuggestionSet,
|
||||
questionID string,
|
||||
eventType string,
|
||||
) error {
|
||||
actorID := types.SessionOwnerIDFromContext(ctx)
|
||||
if principal, ok := types.PrincipalFromContext(ctx); ok {
|
||||
actorID = principal.StorageID()
|
||||
}
|
||||
return s.repo.CreateEvent(ctx, &types.MessageSuggestionEvent{
|
||||
TenantID: set.TenantID,
|
||||
SessionID: set.SessionID,
|
||||
SuggestionSetID: set.ID,
|
||||
QuestionID: questionID,
|
||||
EventType: eventType,
|
||||
ActorID: actorID,
|
||||
})
|
||||
}
|
||||
|
||||
type generatedSuggestionEnvelope struct {
|
||||
Questions []struct {
|
||||
Text string `json:"text"`
|
||||
Category string `json:"category"`
|
||||
} `json:"questions"`
|
||||
}
|
||||
|
||||
func parseGeneratedSuggestions(content string, allowedCategories []string, limit int) (types.SuggestionItems, error) {
|
||||
content = strings.TrimSpace(suggestionThinkBlock.ReplaceAllString(content, ""))
|
||||
start := strings.Index(content, "{")
|
||||
end := strings.LastIndex(content, "}")
|
||||
if start < 0 || end < start {
|
||||
return nil, errors.New("model returned invalid suggestion JSON")
|
||||
}
|
||||
var envelope generatedSuggestionEnvelope
|
||||
if err := json.Unmarshal([]byte(content[start:end+1]), &envelope); err != nil {
|
||||
return nil, fmt.Errorf("decode suggestion JSON: %w", err)
|
||||
}
|
||||
allowed := make(map[string]struct{}, len(allowedCategories))
|
||||
for _, category := range allowedCategories {
|
||||
allowed[category] = struct{}{}
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
items := make(types.SuggestionItems, 0, limit)
|
||||
for _, question := range envelope.Questions {
|
||||
text := strings.TrimSpace(question.Text)
|
||||
if text == "" || len([]rune(text)) > 200 {
|
||||
continue
|
||||
}
|
||||
key := normalizeSuggestionText(text)
|
||||
if _, exists := seen[key]; exists {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
category := question.Category
|
||||
if len(allowed) > 0 {
|
||||
if _, ok := allowed[category]; !ok {
|
||||
category = ""
|
||||
}
|
||||
}
|
||||
items = append(items, types.SuggestionItem{
|
||||
ID: uuid.NewString(),
|
||||
Text: text,
|
||||
Category: category,
|
||||
Source: "model",
|
||||
})
|
||||
if len(items) == limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func mergeSuggestionItems(primary, fallback types.SuggestionItems, limit int) types.SuggestionItems {
|
||||
result := make(types.SuggestionItems, 0, limit)
|
||||
seen := make(map[string]struct{})
|
||||
for _, group := range []types.SuggestionItems{primary, fallback} {
|
||||
for _, item := range group {
|
||||
key := normalizeSuggestionText(item.Text)
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[key]; ok {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
result = append(result, item)
|
||||
if len(result) == limit {
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func normalizeSuggestionText(value string) string {
|
||||
return strings.Map(func(r rune) rune {
|
||||
if unicode.IsSpace(r) || strings.ContainsRune("??!!,,.。::;;\"'", r) {
|
||||
return -1
|
||||
}
|
||||
return unicode.ToLower(r)
|
||||
}, strings.TrimSpace(value))
|
||||
}
|
||||
|
||||
func containsSuggestionID(items types.SuggestionItems, id string) bool {
|
||||
for _, item := range items {
|
||||
if item.ID == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func answerEndsWithQuestion(answer string) bool {
|
||||
answer = strings.TrimSpace(trailingCitationTags.ReplaceAllString(answer, ""))
|
||||
return strings.HasSuffix(answer, "?") || strings.HasSuffix(answer, "?")
|
||||
}
|
||||
|
||||
func truncateRunes(value string, limit int) string {
|
||||
runes := []rune(value)
|
||||
if len(runes) <= limit {
|
||||
return value
|
||||
}
|
||||
return string(runes[:limit])
|
||||
}
|
||||
|
||||
func suggestionErrorCode(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return "not_found"
|
||||
}
|
||||
value := strings.ToLower(err.Error())
|
||||
switch {
|
||||
case strings.Contains(value, "model"):
|
||||
return "model_error"
|
||||
case strings.Contains(value, "json"):
|
||||
return "invalid_model_output"
|
||||
default:
|
||||
return "generation_error"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func TestParseGeneratedSuggestionsFiltersAndDeduplicates(t *testing.T) {
|
||||
content := "```json\n{\"questions\":[" +
|
||||
"{\"text\":\"如何继续实施?\",\"category\":\"action\"}," +
|
||||
"{\"text\":\"如何继续实施?\",\"category\":\"action\"}," +
|
||||
"{\"text\":\"有哪些风险?\",\"category\":\"unknown\"}" +
|
||||
"]}\n```"
|
||||
items, err := parseGeneratedSuggestions(content, []string{"clarify", "action"}, 3)
|
||||
if err != nil {
|
||||
t.Fatalf("parseGeneratedSuggestions() error = %v", err)
|
||||
}
|
||||
if len(items) != 2 {
|
||||
t.Fatalf("len(items) = %d, want 2", len(items))
|
||||
}
|
||||
if items[0].Category != "action" {
|
||||
t.Fatalf("first category = %q, want action", items[0].Category)
|
||||
}
|
||||
if items[1].Category != "" {
|
||||
t.Fatalf("disallowed category = %q, want empty", items[1].Category)
|
||||
}
|
||||
for _, item := range items {
|
||||
if item.ID == "" || item.Source != "model" {
|
||||
t.Fatalf("item attribution fields are incomplete: %#v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeSuggestionItemsPreservesPriorityAndLimit(t *testing.T) {
|
||||
primary := types.SuggestionItems{{ID: "1", Text: "A?", Source: "model"}}
|
||||
fallback := types.SuggestionItems{
|
||||
{ID: "2", Text: "A?", Source: "faq"},
|
||||
{ID: "3", Text: "B?", Source: "faq"},
|
||||
{ID: "4", Text: "C?", Source: "faq"},
|
||||
}
|
||||
got := mergeSuggestionItems(primary, fallback, 2)
|
||||
if len(got) != 2 || got[0].ID != "1" || got[1].ID != "3" {
|
||||
t.Fatalf("mergeSuggestionItems() = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnswerEndsWithQuestion(t *testing.T) {
|
||||
if !answerEndsWithQuestion("请补充具体时间? ") {
|
||||
t.Fatal("Chinese question ending was not detected")
|
||||
}
|
||||
if answerEndsWithQuestion("结论已经给出。") {
|
||||
t.Fatal("statement was incorrectly detected as question")
|
||||
}
|
||||
if !answerEndsWithQuestion("需要我继续展开吗?\n<kb>1</kb>") {
|
||||
t.Fatal("question before a trailing citation was not detected")
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,7 @@ type sessionService struct {
|
||||
webSearchProviderRepo interfaces.WebSearchProviderRepository // Repository for web search provider entities
|
||||
kbShareService interfaces.KBShareService // Service for KB sharing operations
|
||||
memoryService interfaces.MemoryService // Service for memory operations
|
||||
suggestionRepo interfaces.MessageSuggestionRepository
|
||||
}
|
||||
|
||||
// NewSessionService creates a new session service instance with all required dependencies
|
||||
@@ -63,6 +64,7 @@ func NewSessionService(cfg *config.Config,
|
||||
webSearchProviderRepo interfaces.WebSearchProviderRepository,
|
||||
kbShareService interfaces.KBShareService,
|
||||
memoryService interfaces.MemoryService,
|
||||
suggestionRepo interfaces.MessageSuggestionRepository,
|
||||
) interfaces.SessionService {
|
||||
return &sessionService{
|
||||
cfg: cfg,
|
||||
@@ -79,6 +81,7 @@ func NewSessionService(cfg *config.Config,
|
||||
webSearchProviderRepo: webSearchProviderRepo,
|
||||
kbShareService: kbShareService,
|
||||
memoryService: memoryService,
|
||||
suggestionRepo: suggestionRepo,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,6 +351,11 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
|
||||
if rows == 0 {
|
||||
return apperrors.ErrSessionNotFound
|
||||
}
|
||||
if s.suggestionRepo != nil {
|
||||
if err := s.suggestionRepo.DeleteBySessionID(ctx, tenantID, id); err != nil {
|
||||
logger.Warnf(ctx, "Failed to delete suggestions for session %s: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -405,6 +413,13 @@ func (s *sessionService) BatchDeleteSessions(ctx context.Context, ids []string)
|
||||
})
|
||||
return err
|
||||
}
|
||||
if s.suggestionRepo != nil {
|
||||
for _, id := range visibleIDs {
|
||||
if err := s.suggestionRepo.DeleteBySessionID(ctx, tenantID, id); err != nil {
|
||||
logger.Warnf(ctx, "Failed to delete suggestions for session %s: %v", id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -447,6 +462,13 @@ func (s *sessionService) DeleteAllSessions(ctx context.Context) error {
|
||||
})
|
||||
return err
|
||||
}
|
||||
if s.suggestionRepo != nil && sessions != nil {
|
||||
for _, session := range sessions {
|
||||
if err := s.suggestionRepo.DeleteBySessionID(ctx, tenantID, session.ID); err != nil {
|
||||
logger.Warnf(ctx, "Failed to delete suggestions for session %s: %v", session.ID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "All sessions deleted for tenant %d", tenantID)
|
||||
return nil
|
||||
|
||||
Reference in New Issue
Block a user