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
|
||||
|
||||
@@ -150,6 +150,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(repository.NewKnowledgeTagRepository))
|
||||
must(container.Provide(repository.NewSessionRepository))
|
||||
must(container.Provide(repository.NewMessageRepository))
|
||||
must(container.Provide(repository.NewMessageSuggestionRepository))
|
||||
must(container.Provide(repository.NewModelRepository))
|
||||
must(container.Provide(repository.NewUserRepository))
|
||||
must(container.Provide(repository.NewAuthTokenRepository))
|
||||
@@ -210,6 +211,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(service.NewKnowledgePostProcessService, dig.Name("knowledgePostProcess")))
|
||||
|
||||
must(container.Provide(service.NewMessageService))
|
||||
must(container.Provide(service.NewMessageSuggestionService))
|
||||
must(container.Provide(service.NewMCPServiceService))
|
||||
must(container.Provide(service.NewMCPToolApprovalService))
|
||||
must(container.Provide(service.NewCustomAgentService))
|
||||
@@ -341,6 +343,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(handler.NewTagHandler))
|
||||
must(container.Provide(session.NewHandler))
|
||||
must(container.Provide(handler.NewMessageHandler))
|
||||
must(container.Provide(handler.NewMessageSuggestionHandler))
|
||||
must(container.Provide(handler.NewModelHandler))
|
||||
must(container.Provide(handler.NewEvaluationHandler))
|
||||
must(container.Provide(handler.NewInitializationHandler))
|
||||
|
||||
@@ -93,6 +93,11 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
|
||||
Avatar: req.Avatar,
|
||||
Config: req.Config,
|
||||
}
|
||||
agent.EnsureDefaults()
|
||||
if err := agent.Config.QuestionSuggestions.Validate(); err != nil {
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Creating custom agent, name: %s, agent_mode: %s",
|
||||
secutils.SanitizeForLog(req.Name), req.Config.AgentMode)
|
||||
@@ -332,6 +337,11 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
|
||||
Avatar: req.Avatar,
|
||||
Config: req.Config,
|
||||
}
|
||||
agent.EnsureDefaults()
|
||||
if err := agent.Config.QuestionSuggestions.Validate(); err != nil {
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Updating custom agent, ID: %s, name: %s",
|
||||
secutils.SanitizeForLog(id), secutils.SanitizeForLog(req.Name))
|
||||
|
||||
@@ -30,6 +30,7 @@ type EmbedChannelHandler struct {
|
||||
sessionService interfaces.SessionService
|
||||
sessionHandler *session.Handler
|
||||
messageHandler *MessageHandler
|
||||
suggestionHandler *MessageSuggestionHandler
|
||||
mcpOAuthHandler *MCPOAuthHandler
|
||||
mcpServiceHandler *MCPServiceHandler
|
||||
redis *redis.Client
|
||||
@@ -40,6 +41,7 @@ func NewEmbedChannelHandler(
|
||||
sessionService interfaces.SessionService,
|
||||
sessionHandler *session.Handler,
|
||||
messageHandler *MessageHandler,
|
||||
suggestionHandler *MessageSuggestionHandler,
|
||||
mcpOAuthHandler *MCPOAuthHandler,
|
||||
mcpServiceHandler *MCPServiceHandler,
|
||||
redisClient *redis.Client,
|
||||
@@ -49,6 +51,7 @@ func NewEmbedChannelHandler(
|
||||
sessionService: sessionService,
|
||||
sessionHandler: sessionHandler,
|
||||
messageHandler: messageHandler,
|
||||
suggestionHandler: suggestionHandler,
|
||||
mcpOAuthHandler: mcpOAuthHandler,
|
||||
mcpServiceHandler: mcpServiceHandler,
|
||||
redis: redisClient,
|
||||
@@ -462,6 +465,45 @@ func (h *EmbedChannelHandler) EmbedStopSession(c *gin.Context) {
|
||||
h.sessionHandler.StopSession(c)
|
||||
}
|
||||
|
||||
func (h *EmbedChannelHandler) EmbedEnsureMessageSuggestions(c *gin.Context) {
|
||||
if err := h.ensureEmbedSession(c); err != nil {
|
||||
return
|
||||
}
|
||||
ch, _ := middleware.EmbedChannelFromContext(c.Request.Context())
|
||||
if ch == nil || !ch.ShowSuggestedQuestions || h.suggestionHandler == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{
|
||||
"status": "suppressed", "suppression_reason": "channel_disabled", "questions": []any{},
|
||||
}})
|
||||
return
|
||||
}
|
||||
h.suggestionHandler.Ensure(c)
|
||||
}
|
||||
|
||||
func (h *EmbedChannelHandler) EmbedGetMessageSuggestions(c *gin.Context) {
|
||||
if err := h.ensureEmbedSession(c); err != nil {
|
||||
return
|
||||
}
|
||||
ch, _ := middleware.EmbedChannelFromContext(c.Request.Context())
|
||||
if ch == nil || !ch.ShowSuggestedQuestions || h.suggestionHandler == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{
|
||||
"status": "suppressed", "suppression_reason": "channel_disabled", "questions": []any{},
|
||||
}})
|
||||
return
|
||||
}
|
||||
h.suggestionHandler.Get(c)
|
||||
}
|
||||
|
||||
func (h *EmbedChannelHandler) EmbedRecordSuggestionEvent(c *gin.Context) {
|
||||
if err := h.ensureEmbedSession(c); err != nil {
|
||||
return
|
||||
}
|
||||
if h.suggestionHandler == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "suggestion service unavailable"})
|
||||
return
|
||||
}
|
||||
h.suggestionHandler.RecordEvent(c)
|
||||
}
|
||||
|
||||
func (h *EmbedChannelHandler) EmbedResolveMCPOAuth(c *gin.Context) {
|
||||
if err := h.ensureEmbedSession(c); err != nil {
|
||||
return
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type MessageSuggestionHandler struct {
|
||||
service interfaces.MessageSuggestionService
|
||||
}
|
||||
|
||||
func NewMessageSuggestionHandler(service interfaces.MessageSuggestionService) *MessageSuggestionHandler {
|
||||
return &MessageSuggestionHandler{service: service}
|
||||
}
|
||||
|
||||
type EnsureMessageSuggestionsRequest struct {
|
||||
Regenerate bool `json:"regenerate"`
|
||||
}
|
||||
|
||||
type SuggestionEventRequest struct {
|
||||
SuggestionSetID string `json:"suggestion_set_id" binding:"required"`
|
||||
QuestionID string `json:"question_id"`
|
||||
EventType string `json:"event_type" binding:"required"`
|
||||
}
|
||||
|
||||
// Ensure godoc
|
||||
// @Summary 确保生成回答后推荐问题
|
||||
// @Description 对已完成的助手消息异步生成或重新生成推荐问题;相同配置快照会复用持久化结果
|
||||
// @Tags 会话
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param session_id path string true "会话 ID"
|
||||
// @Param message_id path string true "助手消息 ID"
|
||||
// @Param request body EnsureMessageSuggestionsRequest false "生成选项"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Success 202 {object} map[string]interface{}
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /sessions/{session_id}/messages/{message_id}/suggestions [post]
|
||||
func (h *MessageSuggestionHandler) Ensure(c *gin.Context) {
|
||||
var request EnsureMessageSuggestionsRequest
|
||||
if c.Request.ContentLength > 0 {
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
c.Error(apperrors.NewBadRequestError("invalid request body"))
|
||||
return
|
||||
}
|
||||
}
|
||||
set, err := h.service.EnsureFollowUps(
|
||||
c.Request.Context(),
|
||||
secutils.SanitizeForLog(c.Param("session_id")),
|
||||
secutils.SanitizeForLog(c.Param("message_id")),
|
||||
request.Regenerate,
|
||||
)
|
||||
if err != nil {
|
||||
h.writeError(c, err)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if set != nil && set.Status == "generating" {
|
||||
status = http.StatusAccepted
|
||||
}
|
||||
c.JSON(status, gin.H{"success": true, "data": set})
|
||||
}
|
||||
|
||||
// Get godoc
|
||||
// @Summary 获取回答后推荐问题
|
||||
// @Tags 会话
|
||||
// @Produce json
|
||||
// @Param session_id path string true "会话 ID"
|
||||
// @Param message_id path string true "助手消息 ID"
|
||||
// @Success 200 {object} map[string]interface{}
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /sessions/{session_id}/messages/{message_id}/suggestions [get]
|
||||
func (h *MessageSuggestionHandler) Get(c *gin.Context) {
|
||||
set, err := h.service.GetFollowUps(
|
||||
c.Request.Context(),
|
||||
messageSuggestionSessionID(c),
|
||||
secutils.SanitizeForLog(c.Param("message_id")),
|
||||
)
|
||||
if err != nil {
|
||||
h.writeError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "data": set})
|
||||
}
|
||||
|
||||
func messageSuggestionSessionID(c *gin.Context) string {
|
||||
sessionID := c.Param("session_id")
|
||||
if sessionID == "" {
|
||||
sessionID = c.Param("id")
|
||||
}
|
||||
return secutils.SanitizeForLog(sessionID)
|
||||
}
|
||||
|
||||
// RecordEvent godoc
|
||||
// @Summary 上报推荐问题事件
|
||||
// @Description 记录曝光、点击或关闭事件
|
||||
// @Tags 会话
|
||||
// @Accept json
|
||||
// @Param session_id path string true "会话 ID"
|
||||
// @Param request body SuggestionEventRequest true "事件"
|
||||
// @Success 204
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /sessions/{session_id}/suggestion-events [post]
|
||||
func (h *MessageSuggestionHandler) RecordEvent(c *gin.Context) {
|
||||
var request SuggestionEventRequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
c.Error(apperrors.NewBadRequestError("invalid request body"))
|
||||
return
|
||||
}
|
||||
err := h.service.RecordEvent(
|
||||
c.Request.Context(),
|
||||
secutils.SanitizeForLog(c.Param("session_id")),
|
||||
strings.TrimSpace(request.SuggestionSetID),
|
||||
strings.TrimSpace(request.QuestionID),
|
||||
strings.TrimSpace(request.EventType),
|
||||
)
|
||||
if err != nil {
|
||||
h.writeError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *MessageSuggestionHandler) writeError(c *gin.Context, err error) {
|
||||
switch {
|
||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||
c.Error(apperrors.NewNotFoundError("suggestions not found"))
|
||||
case strings.Contains(err.Error(), "completed assistant"):
|
||||
c.Error(apperrors.NewBadRequestError(err.Error()))
|
||||
case strings.Contains(err.Error(), "invalid suggestion event"),
|
||||
strings.Contains(err.Error(), "requires question_id"),
|
||||
strings.Contains(err.Error(), "does not belong"),
|
||||
strings.Contains(err.Error(), "not allowed"):
|
||||
c.Error(apperrors.NewBadRequestError(err.Error()))
|
||||
default:
|
||||
logger.Error(c.Request.Context(), "message suggestion operation failed", err)
|
||||
c.Error(apperrors.NewInternalServerError("message suggestion operation failed"))
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,8 @@ import (
|
||||
|
||||
// Handler handles all HTTP requests related to conversation sessions
|
||||
type Handler struct {
|
||||
messageService interfaces.MessageService // Service for managing messages
|
||||
messageService interfaces.MessageService // Service for managing messages
|
||||
suggestionService interfaces.MessageSuggestionService
|
||||
sessionService interfaces.SessionService // Service for managing sessions
|
||||
streamManager interfaces.StreamManager // Manager for handling streaming responses
|
||||
config *config.Config // Application configuration
|
||||
@@ -35,6 +36,7 @@ type Handler struct {
|
||||
func NewHandler(
|
||||
sessionService interfaces.SessionService,
|
||||
messageService interfaces.MessageService,
|
||||
suggestionService interfaces.MessageSuggestionService,
|
||||
streamManager interfaces.StreamManager,
|
||||
config *config.Config,
|
||||
knowledgebaseService interfaces.KnowledgeBaseService,
|
||||
@@ -51,6 +53,7 @@ func NewHandler(
|
||||
return &Handler{
|
||||
sessionService: sessionService,
|
||||
messageService: messageService,
|
||||
suggestionService: suggestionService,
|
||||
streamManager: streamManager,
|
||||
config: config,
|
||||
knowledgebaseService: knowledgebaseService,
|
||||
|
||||
@@ -277,18 +277,19 @@ func createAgentQueryEvent(sessionID, assistantMessageID string) interfaces.Stre
|
||||
}
|
||||
|
||||
// createUserMessage creates a user message and returns the created message.
|
||||
func (h *Handler) createUserMessage(ctx context.Context, sessionID, query, requestID string, mentionedItems types.MentionedItems, images types.MessageImages, attachments types.MessageAttachments, channel string) (*types.Message, error) {
|
||||
func (h *Handler) createUserMessage(ctx context.Context, sessionID, query, requestID string, mentionedItems types.MentionedItems, images types.MessageImages, attachments types.MessageAttachments, channel string, attribution *types.SuggestionAttribution) (*types.Message, error) {
|
||||
return h.messageService.CreateMessage(ctx, &types.Message{
|
||||
SessionID: sessionID,
|
||||
Role: "user",
|
||||
Content: query,
|
||||
RequestID: requestID,
|
||||
CreatedAt: time.Now(),
|
||||
IsCompleted: true,
|
||||
MentionedItems: mentionedItems,
|
||||
Images: images,
|
||||
Attachments: attachments,
|
||||
Channel: channel,
|
||||
SessionID: sessionID,
|
||||
Role: "user",
|
||||
Content: query,
|
||||
RequestID: requestID,
|
||||
CreatedAt: time.Now(),
|
||||
IsCompleted: true,
|
||||
MentionedItems: mentionedItems,
|
||||
Images: images,
|
||||
Attachments: attachments,
|
||||
Channel: channel,
|
||||
ExecutionContext: types.MessageExecutionContext{SuggestionAttribution: attribution},
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+149
-46
@@ -2,6 +2,7 @@ package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -20,30 +21,31 @@ import (
|
||||
|
||||
// qaRequestContext holds all the common data needed for QA requests
|
||||
type qaRequestContext struct {
|
||||
ctx context.Context
|
||||
c *gin.Context
|
||||
sessionID string
|
||||
requestID string
|
||||
receivedAt time.Time // Wall-clock time the handler started processing the request
|
||||
query string
|
||||
session *types.Session
|
||||
customAgent *types.CustomAgent
|
||||
assistantMessage *types.Message
|
||||
knowledgeBaseIDs []string
|
||||
knowledgeIDs []string
|
||||
tagScopes []types.TagScope
|
||||
tagIDs []string
|
||||
mcpServiceIDs []string
|
||||
skillNames []string
|
||||
summaryModelID string
|
||||
webSearchEnabled bool
|
||||
enableMemory bool // Whether memory feature is enabled
|
||||
mentionedItems types.MentionedItems
|
||||
effectiveTenantID uint64 // when using shared agent, tenant ID for model/KB/MCP resolution; 0 = use context tenant
|
||||
images []ImageAttachment // Uploaded images with analysis text
|
||||
userMessageID string // Created user message ID (populated after createUserMessage)
|
||||
channel string // Source channel: "web", "api", "im", etc.
|
||||
attachments types.MessageAttachments // Processed file attachments
|
||||
ctx context.Context
|
||||
c *gin.Context
|
||||
sessionID string
|
||||
requestID string
|
||||
receivedAt time.Time // Wall-clock time the handler started processing the request
|
||||
query string
|
||||
session *types.Session
|
||||
customAgent *types.CustomAgent
|
||||
assistantMessage *types.Message
|
||||
knowledgeBaseIDs []string
|
||||
knowledgeIDs []string
|
||||
tagScopes []types.TagScope
|
||||
tagIDs []string
|
||||
mcpServiceIDs []string
|
||||
skillNames []string
|
||||
summaryModelID string
|
||||
webSearchEnabled bool
|
||||
enableMemory bool // Whether memory feature is enabled
|
||||
mentionedItems types.MentionedItems
|
||||
effectiveTenantID uint64 // when using shared agent, tenant ID for model/KB/MCP resolution; 0 = use context tenant
|
||||
images []ImageAttachment // Uploaded images with analysis text
|
||||
userMessageID string // Created user message ID (populated after createUserMessage)
|
||||
channel string // Source channel: "web", "api", "im", etc.
|
||||
attachments types.MessageAttachments // Processed file attachments
|
||||
suggestionAttribution *types.SuggestionAttribution
|
||||
|
||||
// Snapshot of the request fields needed to persist the input-bar state
|
||||
// for session restoration. Kept verbatim from the request so we record
|
||||
@@ -102,6 +104,11 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
||||
logger.Error(ctx, "Query content is empty")
|
||||
return nil, nil, errors.NewBadRequestError("Query content cannot be empty")
|
||||
}
|
||||
if h.suggestionService != nil && request.SuggestionAttribution != nil {
|
||||
if err := h.suggestionService.ValidateAttribution(ctx, sessionID, request.Query, request.SuggestionAttribution); err != nil {
|
||||
return nil, nil, errors.NewBadRequestError("invalid suggestion attribution")
|
||||
}
|
||||
}
|
||||
|
||||
// SSRF protection: strip client-supplied URL/Caption fields from image attachments.
|
||||
// The URL field must only be populated server-side by saveImageAttachments; an
|
||||
@@ -259,6 +266,18 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
||||
tagIDs := dedupRequestStrings(append(request.TagIDs, mentionedIDsByType(request.MentionedItems, "tag")...))
|
||||
mcpServiceIDs := dedupRequestStrings(append(request.MCPServiceIDs, mentionedIDsByType(request.MentionedItems, "mcp")...))
|
||||
skillNames := dedupRequestStrings(append(request.SkillNames, mentionedIDsByType(request.MentionedItems, "skill")...))
|
||||
executionContext, agentID, agentTenantID, modelID := buildMessageExecutionContext(
|
||||
ctx,
|
||||
customAgent,
|
||||
effectiveTenantID,
|
||||
request.SummaryModelID,
|
||||
secutils.SanitizeForLogArray(kbIDs),
|
||||
secutils.SanitizeForLogArray(knowledgeIDs),
|
||||
secutils.SanitizeForLogArray(tagIDs),
|
||||
secutils.SanitizeForLogArray(mcpServiceIDs),
|
||||
secutils.SanitizeForLogArray(skillNames),
|
||||
request.WebSearchEnabled,
|
||||
)
|
||||
|
||||
// Build request context
|
||||
reqCtx := &qaRequestContext{
|
||||
@@ -271,33 +290,108 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
||||
session: session,
|
||||
customAgent: customAgent,
|
||||
assistantMessage: &types.Message{
|
||||
SessionID: sessionID,
|
||||
Role: "assistant",
|
||||
RequestID: c.GetString(types.RequestIDContextKey.String()),
|
||||
IsCompleted: false,
|
||||
Channel: request.Channel,
|
||||
SessionID: sessionID,
|
||||
Role: "assistant",
|
||||
RequestID: c.GetString(types.RequestIDContextKey.String()),
|
||||
IsCompleted: false,
|
||||
Channel: request.Channel,
|
||||
AgentID: agentID,
|
||||
AgentTenantID: agentTenantID,
|
||||
ModelID: modelID,
|
||||
ExecutionContext: executionContext,
|
||||
},
|
||||
knowledgeBaseIDs: secutils.SanitizeForLogArray(kbIDs),
|
||||
knowledgeIDs: secutils.SanitizeForLogArray(knowledgeIDs),
|
||||
tagScopes: tagScopes,
|
||||
tagIDs: secutils.SanitizeForLogArray(tagIDs),
|
||||
mcpServiceIDs: secutils.SanitizeForLogArray(mcpServiceIDs),
|
||||
skillNames: secutils.SanitizeForLogArray(skillNames),
|
||||
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
|
||||
webSearchEnabled: request.WebSearchEnabled,
|
||||
enableMemory: enableMemory,
|
||||
mentionedItems: convertMentionedItems(request.MentionedItems),
|
||||
effectiveTenantID: effectiveTenantID,
|
||||
images: request.Images,
|
||||
channel: request.Channel,
|
||||
attachments: processedAttachments,
|
||||
reqAgentEnabled: request.AgentEnabled,
|
||||
reqAgentID: request.AgentID,
|
||||
knowledgeBaseIDs: secutils.SanitizeForLogArray(kbIDs),
|
||||
knowledgeIDs: secutils.SanitizeForLogArray(knowledgeIDs),
|
||||
tagScopes: tagScopes,
|
||||
tagIDs: secutils.SanitizeForLogArray(tagIDs),
|
||||
mcpServiceIDs: secutils.SanitizeForLogArray(mcpServiceIDs),
|
||||
skillNames: secutils.SanitizeForLogArray(skillNames),
|
||||
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
|
||||
webSearchEnabled: request.WebSearchEnabled,
|
||||
enableMemory: enableMemory,
|
||||
mentionedItems: convertMentionedItems(request.MentionedItems),
|
||||
effectiveTenantID: effectiveTenantID,
|
||||
images: request.Images,
|
||||
channel: request.Channel,
|
||||
attachments: processedAttachments,
|
||||
suggestionAttribution: request.SuggestionAttribution,
|
||||
reqAgentEnabled: request.AgentEnabled,
|
||||
reqAgentID: request.AgentID,
|
||||
}
|
||||
|
||||
return reqCtx, &request, nil
|
||||
}
|
||||
|
||||
func buildMessageExecutionContext(
|
||||
ctx context.Context,
|
||||
agent *types.CustomAgent,
|
||||
effectiveTenantID uint64,
|
||||
modelOverride string,
|
||||
knowledgeBaseIDs []string,
|
||||
knowledgeIDs []string,
|
||||
tagIDs []string,
|
||||
mcpServiceIDs []string,
|
||||
skillNames []string,
|
||||
webSearchEnabled bool,
|
||||
) (types.MessageExecutionContext, string, uint64, string) {
|
||||
locale, ok := types.LanguageFromContext(ctx)
|
||||
if !ok {
|
||||
locale = types.DefaultLanguage()
|
||||
}
|
||||
|
||||
snapshot := types.MessageExecutionContext{
|
||||
KnowledgeBaseIDs: knowledgeBaseIDs,
|
||||
KnowledgeIDs: knowledgeIDs,
|
||||
TagIDs: tagIDs,
|
||||
MCPServiceIDs: mcpServiceIDs,
|
||||
SkillNames: skillNames,
|
||||
WebSearchEnabled: webSearchEnabled,
|
||||
Locale: locale,
|
||||
}
|
||||
if agent == nil {
|
||||
return snapshot, "", effectiveTenantID, modelOverride
|
||||
}
|
||||
|
||||
modelID := modelOverride
|
||||
if modelID == "" {
|
||||
modelID = agent.Config.ModelID
|
||||
}
|
||||
agentTenantID := effectiveTenantID
|
||||
if agentTenantID == 0 {
|
||||
agentTenantID = agent.TenantID
|
||||
}
|
||||
|
||||
// Marshal/unmarshal gives the snapshot independent backing slices, so a
|
||||
// later agent edit cannot mutate an in-flight message context.
|
||||
if agent.Config.QuestionSuggestions != nil {
|
||||
if encoded, err := json.Marshal(agent.Config.QuestionSuggestions); err == nil {
|
||||
var suggestions types.QuestionSuggestionConfig
|
||||
if json.Unmarshal(encoded, &suggestions) == nil {
|
||||
snapshot.QuestionSuggestions = &suggestions
|
||||
}
|
||||
}
|
||||
}
|
||||
hashInput := struct {
|
||||
QuestionSuggestions *types.QuestionSuggestionConfig `json:"question_suggestions,omitempty"`
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
|
||||
TagIDs []string `json:"tag_ids,omitempty"`
|
||||
ModelID string `json:"model_id,omitempty"`
|
||||
}{
|
||||
QuestionSuggestions: snapshot.QuestionSuggestions,
|
||||
KnowledgeBaseIDs: knowledgeBaseIDs,
|
||||
KnowledgeIDs: knowledgeIDs,
|
||||
TagIDs: tagIDs,
|
||||
ModelID: modelID,
|
||||
}
|
||||
if encoded, err := json.Marshal(hashInput); err == nil {
|
||||
hash := sha256.Sum256(encoded)
|
||||
snapshot.AgentConfigHash = fmt.Sprintf("%x", hash[:])
|
||||
}
|
||||
|
||||
return snapshot, agent.ID, agentTenantID, modelID
|
||||
}
|
||||
|
||||
// resolveEnableMemory decides whether the memory pipeline runs for this
|
||||
// request. See the call-site comment in parseQARequest for the resolution
|
||||
// order. Lookup errors are logged but never propagate — a failure to read
|
||||
@@ -688,7 +782,7 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle
|
||||
}
|
||||
|
||||
// Create user message
|
||||
userMsg, err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems, convertImageAttachments(reqCtx.images), reqCtx.attachments, reqCtx.channel)
|
||||
userMsg, err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems, convertImageAttachments(reqCtx.images), reqCtx.attachments, reqCtx.channel, reqCtx.suggestionAttribution)
|
||||
if err != nil {
|
||||
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
@@ -964,4 +1058,13 @@ func (h *Handler) completeAssistantMessage(ctx context.Context, assistantMessage
|
||||
// Use WithoutCancel so the goroutine survives after the HTTP request context is done.
|
||||
bgCtx := context.WithoutCancel(ctx)
|
||||
go h.messageService.IndexMessageToKB(bgCtx, userQuery, assistantMessage.Content, assistantMessage.ID, assistantMessage.SessionID)
|
||||
if userQuery != "" && h.suggestionService != nil {
|
||||
go func() {
|
||||
if _, err := h.suggestionService.EnsureFollowUps(
|
||||
bgCtx, assistantMessage.SessionID, assistantMessage.ID, false,
|
||||
); err != nil {
|
||||
logger.Warnf(bgCtx, "follow-up suggestion generation failed for message %s: %v", assistantMessage.ID, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,10 +65,11 @@ type CreateKnowledgeQARequest struct {
|
||||
// user's personal memory setting doesn't leak into a widget
|
||||
// context; older clients that still send a literal bool also
|
||||
// land here (back-compat).
|
||||
EnableMemory *bool `json:"enable_memory,omitempty"`
|
||||
Images []ImageAttachment `json:"images"` // Attached images for multimodal chat
|
||||
AttachmentUploads []AttachmentUpload `json:"attachment_uploads,omitempty"` // Attached files (documents, audio, etc.)
|
||||
Channel string `json:"channel"` // Source channel: "web", "api", "im", etc.
|
||||
EnableMemory *bool `json:"enable_memory,omitempty"`
|
||||
Images []ImageAttachment `json:"images"` // Attached images for multimodal chat
|
||||
AttachmentUploads []AttachmentUpload `json:"attachment_uploads,omitempty"` // Attached files (documents, audio, etc.)
|
||||
Channel string `json:"channel"` // Source channel: "web", "api", "im", etc.
|
||||
SuggestionAttribution *types.SuggestionAttribution `json:"suggestion_attribution,omitempty"`
|
||||
}
|
||||
|
||||
// AttachmentUpload represents a file attachment upload from the client
|
||||
|
||||
@@ -60,6 +60,7 @@ type RouterParams struct {
|
||||
ChunkHandler *handler.ChunkHandler
|
||||
SessionHandler *session.Handler
|
||||
MessageHandler *handler.MessageHandler
|
||||
MessageSuggestionHandler *handler.MessageSuggestionHandler
|
||||
ModelHandler *handler.ModelHandler
|
||||
ModelCredentialsHandler *handler.ModelCredentialsHandler
|
||||
EvaluationHandler *handler.EvaluationHandler
|
||||
@@ -221,7 +222,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
RegisterKnowledgeRoutes(v1, params.KnowledgeHandler, rbacGuards)
|
||||
RegisterFAQRoutes(v1, params.FAQHandler, rbacGuards)
|
||||
RegisterChunkRoutes(v1, params.ChunkHandler, rbacGuards)
|
||||
RegisterSessionRoutes(v1, params.SessionHandler, rbacGuards)
|
||||
RegisterSessionRoutes(v1, params.SessionHandler, params.MessageSuggestionHandler, rbacGuards)
|
||||
RegisterChatRoutes(v1, params.SessionHandler, rbacGuards)
|
||||
RegisterMessageRoutes(v1, params.MessageHandler, rbacGuards)
|
||||
RegisterModelRoutes(v1, params.ModelHandler, params.ModelCredentialsHandler, rbacGuards)
|
||||
@@ -505,7 +506,12 @@ func RegisterMessageRoutes(r *gin.RouterGroup, handler *handler.MessageHandler,
|
||||
// the message routes above. A future refactor can introduce
|
||||
// per-session ownership in the middleware layer the same way KB/agent
|
||||
// routes do today.
|
||||
func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGuards) {
|
||||
func RegisterSessionRoutes(
|
||||
r *gin.RouterGroup,
|
||||
handler *session.Handler,
|
||||
suggestionHandler *handler.MessageSuggestionHandler,
|
||||
g *rbacGuards,
|
||||
) {
|
||||
// Sessions are per-user chat state, not knowledge-base content. The
|
||||
// chat capability lets a scoped key run the full conversation flow
|
||||
// (create/manage its own sessions) without full tenant access.
|
||||
@@ -528,6 +534,13 @@ func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbac
|
||||
sessions.DELETE("/:id/pin", handler.UnpinSession)
|
||||
// 继续接收活跃流
|
||||
sessions.GET("/continue-stream/:session_id", handler.ContinueStream)
|
||||
if suggestionHandler != nil {
|
||||
// Gin requires wildcard names to be identical within the same HTTP-method
|
||||
// radix tree. Existing GET session routes use :id, so keep that name here.
|
||||
sessions.GET("/:id/messages/:message_id/suggestions", suggestionHandler.Get)
|
||||
sessions.POST("/:session_id/messages/:message_id/suggestions", suggestionHandler.Ensure)
|
||||
sessions.POST("/:session_id/suggestion-events", suggestionHandler.RecordEvent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1256,6 +1269,9 @@ func RegisterEmbedPublicRoutes(
|
||||
embed.POST("/agent-chat/:session_id", embedHandler.EmbedAgentChat)
|
||||
embed.GET("/messages/:session_id/load", embedHandler.EmbedLoadMessages)
|
||||
embed.POST("/sessions/:session_id/stop", embedHandler.EmbedStopSession)
|
||||
embed.GET("/sessions/:session_id/messages/:message_id/suggestions", embedHandler.EmbedGetMessageSuggestions)
|
||||
embed.POST("/sessions/:session_id/messages/:message_id/suggestions", embedHandler.EmbedEnsureMessageSuggestions)
|
||||
embed.POST("/sessions/:session_id/suggestion-events", embedHandler.EmbedRecordSuggestionEvent)
|
||||
embed.POST("/sessions/:session_id/events", embedHandler.EmbedRelayWebhookEvent)
|
||||
embed.POST("/sessions/:session_id/mcp-oauth-resolutions/:pending_id", embedHandler.EmbedResolveMCPOAuth)
|
||||
embed.POST("/sessions/:session_id/mcp-oauth-resolutions/:pending_id/cancel", embedHandler.EmbedCancelMCPOAuth)
|
||||
|
||||
@@ -16,7 +16,7 @@ func TestConversationRoutesDeclareChatCapability(t *testing.T) {
|
||||
g := &rbacGuards{}
|
||||
v1 := gin.New().Group("/api/v1")
|
||||
|
||||
RegisterSessionRoutes(v1, &sessionhandler.Handler{}, g)
|
||||
RegisterSessionRoutes(v1, &sessionhandler.Handler{}, &handler.MessageSuggestionHandler{}, g)
|
||||
RegisterChatRoutes(v1, &sessionhandler.Handler{}, g)
|
||||
RegisterMessageRoutes(v1, &handler.MessageHandler{}, g)
|
||||
|
||||
@@ -25,6 +25,9 @@ func TestConversationRoutesDeclareChatCapability(t *testing.T) {
|
||||
path string
|
||||
}{
|
||||
{http.MethodPost, "/api/v1/sessions"},
|
||||
{http.MethodGet, "/api/v1/sessions/:id/messages/:message_id/suggestions"},
|
||||
{http.MethodPost, "/api/v1/sessions/:session_id/messages/:message_id/suggestions"},
|
||||
{http.MethodPost, "/api/v1/sessions/:session_id/suggestion-events"},
|
||||
{http.MethodPost, "/api/v1/knowledge-chat/:session_id"},
|
||||
{http.MethodPost, "/api/v1/agent-chat/:session_id"},
|
||||
{http.MethodGet, "/api/v1/messages/:session_id/load"},
|
||||
|
||||
@@ -3,6 +3,8 @@ package types
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -245,9 +247,134 @@ type CustomAgentConfig struct {
|
||||
// under config/prompt_templates/intent_prompts.yaml.
|
||||
IntentPrompts map[string]string `yaml:"intent_prompts" json:"intent_prompts,omitempty"`
|
||||
|
||||
// ===== Suggested Prompts =====
|
||||
// 推荐问题列表,用于在前端对话面板展示快捷提问
|
||||
SuggestedPrompts []string `yaml:"suggested_prompts" json:"suggested_prompts,omitempty"`
|
||||
// ===== Conversation Question Suggestions =====
|
||||
// QuestionSuggestions owns both the static/knowledge-backed prompts shown
|
||||
// before the first user turn and the contextual follow-up questions shown
|
||||
// after a completed assistant answer.
|
||||
QuestionSuggestions *QuestionSuggestionConfig `yaml:"question_suggestions,omitempty" json:"question_suggestions,omitempty"`
|
||||
}
|
||||
|
||||
const (
|
||||
SuggestionModeCurated = "curated"
|
||||
SuggestionModeKnowledge = "knowledge"
|
||||
SuggestionModeGenerated = "generated"
|
||||
SuggestionModeHybrid = "hybrid"
|
||||
|
||||
SuggestionCategoryClarify = "clarify"
|
||||
SuggestionCategoryDeepen = "deepen"
|
||||
SuggestionCategoryAction = "action"
|
||||
)
|
||||
|
||||
// QuestionSuggestionConfig is the agent-owned configuration for question
|
||||
// suggestions. Channel settings may suppress rendering, but never override
|
||||
// this content/generation policy.
|
||||
type QuestionSuggestionConfig struct {
|
||||
Starters StarterSuggestionConfig `yaml:"starters" json:"starters"`
|
||||
FollowUps FollowUpSuggestionConfig `yaml:"follow_ups" json:"follow_ups"`
|
||||
}
|
||||
|
||||
// StarterSuggestionConfig controls prompts shown before the first user turn.
|
||||
type StarterSuggestionConfig struct {
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
Mode string `yaml:"mode" json:"mode"`
|
||||
Items []string `yaml:"items" json:"items"`
|
||||
Count int `yaml:"count" json:"count"`
|
||||
}
|
||||
|
||||
// FollowUpSuggestionConfig controls contextual questions generated after a
|
||||
// completed assistant answer.
|
||||
type FollowUpSuggestionConfig struct {
|
||||
Enabled bool `yaml:"enabled" json:"enabled"`
|
||||
Mode string `yaml:"mode" json:"mode"`
|
||||
Count int `yaml:"count" json:"count"`
|
||||
ModelID string `yaml:"model_id,omitempty" json:"model_id,omitempty"`
|
||||
AdditionalInstruction string `yaml:"additional_instruction,omitempty" json:"additional_instruction,omitempty"`
|
||||
Categories []string `yaml:"categories,omitempty" json:"categories,omitempty"`
|
||||
MaxContextTurns int `yaml:"max_context_turns" json:"max_context_turns"`
|
||||
SuppressOnFallback bool `yaml:"suppress_on_fallback" json:"suppress_on_fallback"`
|
||||
SuppressWhenAnswerAsksQuestion bool `yaml:"suppress_when_answer_asks_question" json:"suppress_when_answer_asks_question"`
|
||||
KnowledgeFallback bool `yaml:"knowledge_fallback" json:"knowledge_fallback"`
|
||||
AllowRegenerate bool `yaml:"allow_regenerate" json:"allow_regenerate"`
|
||||
}
|
||||
|
||||
// EnsureDefaults normalizes suggestion configuration without overriding
|
||||
// explicit enable/disable choices.
|
||||
func (c *QuestionSuggestionConfig) EnsureDefaults() {
|
||||
if c.Starters.Mode == "" {
|
||||
c.Starters.Mode = SuggestionModeHybrid
|
||||
}
|
||||
if c.Starters.Count <= 0 {
|
||||
c.Starters.Count = 6
|
||||
}
|
||||
if c.Starters.Items == nil {
|
||||
c.Starters.Items = []string{}
|
||||
}
|
||||
if c.FollowUps.Mode == "" {
|
||||
c.FollowUps.Mode = SuggestionModeHybrid
|
||||
}
|
||||
if c.FollowUps.Count <= 0 {
|
||||
c.FollowUps.Count = 3
|
||||
}
|
||||
if c.FollowUps.MaxContextTurns <= 0 {
|
||||
c.FollowUps.MaxContextTurns = 2
|
||||
}
|
||||
if len(c.FollowUps.Categories) == 0 {
|
||||
c.FollowUps.Categories = []string{
|
||||
SuggestionCategoryClarify,
|
||||
SuggestionCategoryDeepen,
|
||||
SuggestionCategoryAction,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate rejects invalid agent-authored suggestion settings before they are
|
||||
// persisted or used to incur a model call.
|
||||
func (c *QuestionSuggestionConfig) Validate() error {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
if c.Starters.Count < 1 || c.Starters.Count > 8 {
|
||||
return fmt.Errorf("starter suggestion count must be between 1 and 8")
|
||||
}
|
||||
if c.FollowUps.Count < 1 || c.FollowUps.Count > 5 {
|
||||
return fmt.Errorf("follow-up suggestion count must be between 1 and 5")
|
||||
}
|
||||
if c.FollowUps.MaxContextTurns < 1 || c.FollowUps.MaxContextTurns > 5 {
|
||||
return fmt.Errorf("follow-up max_context_turns must be between 1 and 5")
|
||||
}
|
||||
if !oneOf(c.Starters.Mode, SuggestionModeCurated, SuggestionModeKnowledge, SuggestionModeHybrid) {
|
||||
return fmt.Errorf("invalid starter suggestion mode %q", c.Starters.Mode)
|
||||
}
|
||||
if !oneOf(c.FollowUps.Mode, SuggestionModeGenerated, SuggestionModeKnowledge, SuggestionModeHybrid) {
|
||||
return fmt.Errorf("invalid follow-up suggestion mode %q", c.FollowUps.Mode)
|
||||
}
|
||||
for i, item := range c.Starters.Items {
|
||||
trimmed := strings.TrimSpace(item)
|
||||
if trimmed == "" {
|
||||
return fmt.Errorf("starter suggestion %d cannot be empty", i+1)
|
||||
}
|
||||
if len([]rune(trimmed)) > 200 {
|
||||
return fmt.Errorf("starter suggestion %d exceeds 200 characters", i+1)
|
||||
}
|
||||
}
|
||||
if len([]rune(strings.TrimSpace(c.FollowUps.AdditionalInstruction))) > 2000 {
|
||||
return fmt.Errorf("follow-up additional_instruction exceeds 2000 characters")
|
||||
}
|
||||
for _, category := range c.FollowUps.Categories {
|
||||
if !oneOf(category, SuggestionCategoryClarify, SuggestionCategoryDeepen, SuggestionCategoryAction) {
|
||||
return fmt.Errorf("invalid follow-up suggestion category %q", category)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func oneOf(value string, allowed ...string) bool {
|
||||
for _, candidate := range allowed {
|
||||
if value == candidate {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Value implements driver.Valuer interface for CustomAgentConfig
|
||||
@@ -282,6 +409,32 @@ func (a *CustomAgent) EnsureDefaults() {
|
||||
if a == nil {
|
||||
return
|
||||
}
|
||||
if a.Config.QuestionSuggestions == nil {
|
||||
a.Config.QuestionSuggestions = &QuestionSuggestionConfig{
|
||||
Starters: StarterSuggestionConfig{
|
||||
Enabled: true,
|
||||
Mode: SuggestionModeHybrid,
|
||||
Items: []string{},
|
||||
Count: 6,
|
||||
},
|
||||
FollowUps: FollowUpSuggestionConfig{
|
||||
Enabled: false,
|
||||
Mode: SuggestionModeHybrid,
|
||||
Count: 3,
|
||||
MaxContextTurns: 2,
|
||||
SuppressOnFallback: true,
|
||||
SuppressWhenAnswerAsksQuestion: true,
|
||||
KnowledgeFallback: true,
|
||||
Categories: []string{
|
||||
SuggestionCategoryClarify,
|
||||
SuggestionCategoryDeepen,
|
||||
SuggestionCategoryAction,
|
||||
},
|
||||
},
|
||||
}
|
||||
} else {
|
||||
a.Config.QuestionSuggestions.EnsureDefaults()
|
||||
}
|
||||
if a.Config.Temperature < 0 {
|
||||
a.Config.Temperature = 0.7
|
||||
}
|
||||
|
||||
@@ -79,6 +79,11 @@ type CustomAgentService interface {
|
||||
// - List of suggested questions
|
||||
// - Possible errors
|
||||
GetSuggestedQuestions(ctx context.Context, agentID string, kbIDs []string, knowledgeIDs []string, tagIDs []string, limit int) ([]types.SuggestedQuestion, error)
|
||||
|
||||
// GetKnowledgeSuggestedQuestions returns only knowledge-derived candidates.
|
||||
// It is independent of whether starter suggestions are enabled and is used
|
||||
// as a source/fallback for contextual follow-up generation.
|
||||
GetKnowledgeSuggestedQuestions(ctx context.Context, agentID string, kbIDs []string, knowledgeIDs []string, tagIDs []string, limit int) ([]types.SuggestedQuestion, error)
|
||||
}
|
||||
|
||||
// CustomAgentRepository defines the custom agent repository interface
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// MessageSuggestionRepository persists generated suggestions and their
|
||||
// product-analytics events. AcquireGeneration serializes duplicate requests
|
||||
// from reconnecting clients with an expiring lease.
|
||||
type MessageSuggestionRepository interface {
|
||||
GetByCacheKey(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
assistantMessageID string,
|
||||
placement string,
|
||||
configHash string,
|
||||
locale string,
|
||||
) (*types.MessageSuggestionSet, error)
|
||||
GetByID(ctx context.Context, tenantID uint64, sessionID string, id string) (*types.MessageSuggestionSet, error)
|
||||
AcquireGeneration(
|
||||
ctx context.Context,
|
||||
set *types.MessageSuggestionSet,
|
||||
regenerate bool,
|
||||
) (*types.MessageSuggestionSet, bool, error)
|
||||
Save(ctx context.Context, set *types.MessageSuggestionSet) error
|
||||
CreateEvent(ctx context.Context, event *types.MessageSuggestionEvent) error
|
||||
DeleteByMessageID(ctx context.Context, tenantID uint64, sessionID string, messageID string) error
|
||||
DeleteBySessionID(ctx context.Context, tenantID uint64, sessionID string) error
|
||||
}
|
||||
|
||||
type MessageSuggestionService interface {
|
||||
EnsureFollowUps(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
assistantMessageID string,
|
||||
regenerate bool,
|
||||
) (*types.MessageSuggestionSet, error)
|
||||
GetFollowUps(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
assistantMessageID string,
|
||||
) (*types.MessageSuggestionSet, error)
|
||||
RecordEvent(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
setID string,
|
||||
questionID string,
|
||||
eventType string,
|
||||
) error
|
||||
ValidateAttribution(ctx context.Context, sessionID string, query string, attribution *types.SuggestionAttribution) error
|
||||
}
|
||||
@@ -216,6 +216,18 @@ type Message struct {
|
||||
RenderedContent string `json:"-" gorm:"type:text;column:rendered_content;default:''"`
|
||||
// Channel indicates the source channel of this message (e.g., "web", "api", "im")
|
||||
Channel string `json:"channel,omitempty" gorm:"type:varchar(50);default:''"`
|
||||
// AgentID is the agent used for this individual assistant turn. Unlike the
|
||||
// session's last_request_state it remains stable when users switch agents.
|
||||
AgentID string `json:"agent_id,omitempty" gorm:"type:varchar(36);default:'';index"`
|
||||
// AgentTenantID is the effective/source tenant used to resolve a shared
|
||||
// agent's models and knowledge. It is intentionally not exposed in JSON.
|
||||
AgentTenantID uint64 `json:"-" gorm:"column:agent_tenant_id;default:0"`
|
||||
// ModelID is the requested/effective chat model binding captured for this
|
||||
// turn. It is useful for reproducibility and suggestion generation.
|
||||
ModelID string `json:"model_id,omitempty" gorm:"type:varchar(64);default:''"`
|
||||
// ExecutionContext stores the non-secret per-turn scope required to safely
|
||||
// generate contextual follow-up questions after the main stream completes.
|
||||
ExecutionContext MessageExecutionContext `json:"-" gorm:"type:jsonb;column:execution_context"`
|
||||
// KnowledgeID links this message to a Knowledge entry in the chat history knowledge base
|
||||
// Used for vector search indexing: when set, the message content has been indexed as a Knowledge passage
|
||||
KnowledgeID string `json:"knowledge_id,omitempty" gorm:"type:varchar(36);index"`
|
||||
@@ -227,6 +239,43 @@ type Message struct {
|
||||
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
|
||||
}
|
||||
|
||||
// MessageExecutionContext is a message-level snapshot of the non-secret
|
||||
// request state used by derived experiences such as follow-up suggestions.
|
||||
type MessageExecutionContext struct {
|
||||
AgentConfigHash string `json:"agent_config_hash,omitempty"`
|
||||
QuestionSuggestions *QuestionSuggestionConfig `json:"question_suggestions,omitempty"`
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
|
||||
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
|
||||
TagIDs []string `json:"tag_ids,omitempty"`
|
||||
MCPServiceIDs []string `json:"mcp_service_ids,omitempty"`
|
||||
SkillNames []string `json:"skill_names,omitempty"`
|
||||
WebSearchEnabled bool `json:"web_search_enabled"`
|
||||
Locale string `json:"locale,omitempty"`
|
||||
SuggestionAttribution *SuggestionAttribution `json:"suggestion_attribution,omitempty"`
|
||||
}
|
||||
|
||||
func (c MessageExecutionContext) Value() (driver.Value, error) {
|
||||
return json.Marshal(c)
|
||||
}
|
||||
|
||||
func (c *MessageExecutionContext) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
*c = MessageExecutionContext{}
|
||||
return nil
|
||||
}
|
||||
var b []byte
|
||||
switch v := value.(type) {
|
||||
case []byte:
|
||||
b = v
|
||||
case string:
|
||||
b = []byte(v)
|
||||
default:
|
||||
*c = MessageExecutionContext{}
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
// AgentSteps represents a collection of agent execution steps
|
||||
// Used for storing agent reasoning process in database
|
||||
type AgentSteps []AgentStep
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
SuggestionPlacementAfterAnswer = "after_answer"
|
||||
|
||||
SuggestionStatusGenerating = "generating"
|
||||
SuggestionStatusReady = "ready"
|
||||
SuggestionStatusSuppressed = "suppressed"
|
||||
SuggestionStatusFailed = "failed"
|
||||
|
||||
SuggestionEventImpression = "impression"
|
||||
SuggestionEventClick = "click"
|
||||
SuggestionEventDismiss = "dismiss"
|
||||
SuggestionEventRegenerate = "regenerate"
|
||||
)
|
||||
|
||||
// SuggestionAttribution is carried by the next user message after a click, so
|
||||
// analytics can distinguish a click from a question that was actually sent.
|
||||
type SuggestionAttribution struct {
|
||||
SuggestionSetID string `json:"suggestion_set_id"`
|
||||
QuestionID string `json:"question_id"`
|
||||
}
|
||||
|
||||
// SuggestionItem is a stable, attributable question rendered to an end user.
|
||||
type SuggestionItem struct {
|
||||
ID string `json:"id"`
|
||||
Text string `json:"text"`
|
||||
Category string `json:"category,omitempty"`
|
||||
Source string `json:"source"`
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
|
||||
}
|
||||
|
||||
type SuggestionItems []SuggestionItem
|
||||
|
||||
func (s SuggestionItems) Value() (driver.Value, error) {
|
||||
if s == nil {
|
||||
s = SuggestionItems{}
|
||||
}
|
||||
return json.Marshal(s)
|
||||
}
|
||||
|
||||
func (s *SuggestionItems) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
*s = SuggestionItems{}
|
||||
return nil
|
||||
}
|
||||
var b []byte
|
||||
switch v := value.(type) {
|
||||
case []byte:
|
||||
b = v
|
||||
case string:
|
||||
b = []byte(v)
|
||||
default:
|
||||
*s = SuggestionItems{}
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, s)
|
||||
}
|
||||
|
||||
// MessageSuggestionSet is the durable generation/cache record for one
|
||||
// assistant message and one effective agent configuration.
|
||||
type MessageSuggestionSet struct {
|
||||
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
SessionID string `json:"session_id" gorm:"type:varchar(36);not null;index"`
|
||||
AssistantMessageID string `json:"assistant_message_id" gorm:"type:varchar(36);not null;index"`
|
||||
AgentID string `json:"agent_id" gorm:"type:varchar(36);not null;index"`
|
||||
AgentTenantID uint64 `json:"-" gorm:"not null;default:0"`
|
||||
Placement string `json:"placement" gorm:"type:varchar(32);not null"`
|
||||
ConfigHash string `json:"config_hash" gorm:"type:varchar(64);not null"`
|
||||
Locale string `json:"locale" gorm:"type:varchar(16);not null;default:''"`
|
||||
Status string `json:"status" gorm:"type:varchar(16);not null;index"`
|
||||
AllowRegenerate bool `json:"allow_regenerate" gorm:"not null;default:false"`
|
||||
SuppressionReason string `json:"suppression_reason,omitempty" gorm:"type:varchar(64);not null;default:''"`
|
||||
Questions SuggestionItems `json:"questions" gorm:"type:jsonb;not null"`
|
||||
ModelID string `json:"model_id,omitempty" gorm:"type:varchar(64);not null;default:''"`
|
||||
PromptTokens int `json:"prompt_tokens,omitempty" gorm:"not null;default:0"`
|
||||
CompletionTokens int `json:"completion_tokens,omitempty" gorm:"not null;default:0"`
|
||||
LatencyMs int64 `json:"latency_ms,omitempty" gorm:"not null;default:0"`
|
||||
ErrorCode string `json:"error_code,omitempty" gorm:"type:varchar(64);not null;default:''"`
|
||||
LeaseUntil *time.Time `json:"-"`
|
||||
GeneratedAt *time.Time `json:"generated_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (MessageSuggestionSet) TableName() string { return "message_suggestion_sets" }
|
||||
|
||||
func (s *MessageSuggestionSet) BeforeCreate(_ *gorm.DB) error {
|
||||
if s.ID == "" {
|
||||
s.ID = uuid.NewString()
|
||||
}
|
||||
if s.Questions == nil {
|
||||
s.Questions = SuggestionItems{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MessageSuggestionEvent stores product analytics separately from the
|
||||
// security audit log. It references question IDs rather than copying text.
|
||||
type MessageSuggestionEvent struct {
|
||||
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
|
||||
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
|
||||
SessionID string `json:"session_id" gorm:"type:varchar(36);not null;index"`
|
||||
SuggestionSetID string `json:"suggestion_set_id" gorm:"type:varchar(36);not null;index"`
|
||||
QuestionID string `json:"question_id,omitempty" gorm:"type:varchar(64);not null;default:''"`
|
||||
EventType string `json:"event_type" gorm:"type:varchar(32);not null;index"`
|
||||
ActorID string `json:"-" gorm:"type:varchar(512);not null;default:''"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"index"`
|
||||
}
|
||||
|
||||
func (MessageSuggestionEvent) TableName() string { return "message_suggestion_events" }
|
||||
@@ -0,0 +1,22 @@
|
||||
package types
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestQuestionSuggestionConfigValidate(t *testing.T) {
|
||||
config := &QuestionSuggestionConfig{
|
||||
Starters: StarterSuggestionConfig{Mode: SuggestionModeHybrid, Count: 6},
|
||||
FollowUps: FollowUpSuggestionConfig{
|
||||
Mode: SuggestionModeHybrid,
|
||||
Count: 3,
|
||||
MaxContextTurns: 2,
|
||||
Categories: []string{SuggestionCategoryClarify, SuggestionCategoryDeepen},
|
||||
},
|
||||
}
|
||||
if err := config.Validate(); err != nil {
|
||||
t.Fatalf("valid config rejected: %v", err)
|
||||
}
|
||||
config.FollowUps.Count = 6
|
||||
if err := config.Validate(); err == nil {
|
||||
t.Fatal("out-of-range follow-up count was accepted")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user