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:
@@ -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