feat: 重构提示词模板系统,新增多场景模板配置支持;优化智能体知识库选择模式,支持全部/指定/禁用三种模式

This commit is contained in:
wizardchen
2025-12-25 18:22:36 +08:00
parent dc1ab5b81d
commit abfe87eaed
32 changed files with 2755 additions and 1102 deletions
+1 -1
View File
@@ -35,7 +35,7 @@ type CreateAgentRequest struct {
// UpdateAgentRequest defines the request body for updating an agent
type UpdateAgentRequest struct {
Name string `json:"name" binding:"required"`
Name string `json:"name"`
Description string `json:"description"`
Avatar string `json:"avatar"`
Type types.CustomAgentType `json:"type"`
+4 -102
View File
@@ -1,7 +1,6 @@
package session
import (
"context"
"net/http"
"github.com/Tencent/WeKnora/internal/config"
@@ -74,75 +73,17 @@ func (h *Handler) CreateSession(c *gin.Context) {
// Validate session creation request
// Sessions are now knowledge-base-independent:
// - KnowledgeBaseID is optional during session creation
// - Knowledge base can be specified in each query request (AgentQA/KnowledgeQA)
// - Agent mode can access multiple knowledge bases via AgentConfig.KnowledgeBases
// - Knowledge base can be switched during conversation
isAgentMode := request.AgentConfig != nil && request.AgentConfig.AgentModeEnabled
hasAgentKnowledgeBases := request.AgentConfig != nil && len(request.AgentConfig.KnowledgeBases) > 0
// - All configuration comes from custom agent at query time
// - Session only stores basic info (tenant ID, title, etc.)
logger.Infof(
ctx,
"Processing session creation request, tenant ID: %d, knowledge base ID: %s, agent mode: %v, agent KBs: %v",
"Processing session creation request, tenant ID: %d",
tenantID,
request.KnowledgeBaseID,
isAgentMode,
hasAgentKnowledgeBases,
)
// Create session object with base properties
createdSession := &types.Session{
TenantID: tenantID.(uint64),
KnowledgeBaseID: request.KnowledgeBaseID,
AgentConfig: request.AgentConfig, // Set agent config if provided
}
// If summary model parameters are empty, set defaults
if request.SessionStrategy != nil {
createdSession.RerankModelID = request.SessionStrategy.RerankModelID
createdSession.SummaryModelID = request.SessionStrategy.SummaryModelID
createdSession.MaxRounds = request.SessionStrategy.MaxRounds
createdSession.EnableRewrite = request.SessionStrategy.EnableRewrite
createdSession.FallbackStrategy = request.SessionStrategy.FallbackStrategy
createdSession.FallbackResponse = request.SessionStrategy.FallbackResponse
createdSession.EmbeddingTopK = request.SessionStrategy.EmbeddingTopK
createdSession.KeywordThreshold = request.SessionStrategy.KeywordThreshold
createdSession.VectorThreshold = request.SessionStrategy.VectorThreshold
createdSession.RerankTopK = request.SessionStrategy.RerankTopK
createdSession.RerankThreshold = request.SessionStrategy.RerankThreshold
if request.SessionStrategy.SummaryParameters != nil {
createdSession.SummaryParameters = request.SessionStrategy.SummaryParameters
} else {
createdSession.SummaryParameters = h.createDefaultSummaryConfig(ctx)
}
h.fillSummaryConfigDefaults(ctx, createdSession.SummaryParameters)
logger.Debug(ctx, "Custom session strategy set")
} else {
tenantInfo, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
h.applyConversationDefaults(ctx, createdSession, tenantInfo)
logger.Debug(ctx, "Using default session strategy")
}
// Fetch knowledge base if KnowledgeBaseID is provided to inherit its model configurations
// If no KB is provided, models will be determined at query time or use tenant/system defaults
if request.KnowledgeBaseID != "" {
kb, err := h.knowledgebaseService.GetKnowledgeBaseByID(ctx, request.KnowledgeBaseID)
if err != nil {
logger.Error(ctx, "Failed to get knowledge base", err)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Use knowledge base's summary model if session doesn't specify it
if createdSession.SummaryModelID == "" {
createdSession.SummaryModelID = kb.SummaryModelID
}
logger.Debugf(ctx, "Knowledge base fetched: %s, summary model: %s",
kb.ID, kb.SummaryModelID)
} else {
logger.Debug(ctx, "No knowledge base ID provided, models will use session strategy or be determined at query time")
TenantID: tenantID.(uint64),
}
// Call service to create session
@@ -162,45 +103,6 @@ func (h *Handler) CreateSession(c *gin.Context) {
})
}
func (h *Handler) applyConversationDefaults(ctx context.Context, session *types.Session, tenant *types.Tenant) {
session.MaxRounds = h.config.Conversation.MaxRounds
session.EnableRewrite = h.config.Conversation.EnableRewrite
session.FallbackStrategy = types.FallbackStrategy(h.config.Conversation.FallbackStrategy)
session.FallbackResponse = h.config.Conversation.FallbackResponse
session.EmbeddingTopK = h.config.Conversation.EmbeddingTopK
session.KeywordThreshold = h.config.Conversation.KeywordThreshold
session.VectorThreshold = h.config.Conversation.VectorThreshold
session.RerankThreshold = h.config.Conversation.RerankThreshold
session.RerankTopK = h.config.Conversation.RerankTopK
session.RerankModelID = ""
session.SummaryModelID = ""
if tenant != nil && tenant.ConversationConfig != nil {
tc := tenant.ConversationConfig
session.MaxRounds = tc.MaxRounds
session.EnableRewrite = tc.EnableRewrite
if tc.FallbackStrategy != "" {
session.FallbackStrategy = types.FallbackStrategy(tc.FallbackStrategy)
}
if tc.FallbackResponse != "" {
session.FallbackResponse = tc.FallbackResponse
}
session.EmbeddingTopK = tc.EmbeddingTopK
session.KeywordThreshold = tc.KeywordThreshold
session.VectorThreshold = tc.VectorThreshold
session.RerankThreshold = tc.RerankThreshold
session.RerankTopK = tc.RerankTopK
if tc.RerankModelID != "" {
session.RerankModelID = tc.RerankModelID
}
if tc.SummaryModelID != "" {
session.SummaryModelID = tc.SummaryModelID
}
}
session.SummaryParameters = h.createDefaultSummaryConfig(ctx)
}
// GetSession godoc
// @Summary 获取会话详情
// @Description 根据ID获取会话详情
+8 -15
View File
@@ -203,20 +203,13 @@ func (h *Handler) createDefaultSummaryConfig(ctx context.Context) *types.Summary
// Override with tenant-level conversation config if available
if tenant != nil && tenant.ConversationConfig != nil {
useSystemPrompt := tenant.ConversationConfig.UseCustomSystemPrompt
if !useSystemPrompt && tenant.ConversationConfig.Prompt != "" {
// Backward compatibility: treat legacy configs without flag as custom
useSystemPrompt = true
}
if useSystemPrompt && tenant.ConversationConfig.Prompt != "" {
// Use custom prompt if provided
if tenant.ConversationConfig.Prompt != "" {
cfg.Prompt = tenant.ConversationConfig.Prompt
}
useContextTemplate := tenant.ConversationConfig.UseCustomContextTemplate
if !useContextTemplate && tenant.ConversationConfig.ContextTemplate != "" {
useContextTemplate = true
}
if useContextTemplate && tenant.ConversationConfig.ContextTemplate != "" {
// Use custom context template if provided
if tenant.ConversationConfig.ContextTemplate != "" {
cfg.ContextTemplate = tenant.ConversationConfig.ContextTemplate
}
if tenant.ConversationConfig.Temperature > 0 {
@@ -242,13 +235,13 @@ func (h *Handler) fillSummaryConfigDefaults(ctx context.Context, config *types.S
var defaultMaxCompletionTokens int
if tenant != nil && tenant.ConversationConfig != nil {
useSystemPrompt := tenant.ConversationConfig.UseCustomSystemPrompt
if useSystemPrompt && tenant.ConversationConfig.Prompt != "" {
// Use custom prompt if provided
if tenant.ConversationConfig.Prompt != "" {
defaultPrompt = tenant.ConversationConfig.Prompt
}
useContextTemplate := tenant.ConversationConfig.UseCustomContextTemplate
if useContextTemplate && tenant.ConversationConfig.ContextTemplate != "" {
// Use custom context template if provided
if tenant.ConversationConfig.ContextTemplate != "" {
defaultContextTemplate = tenant.ConversationConfig.ContextTemplate
}
defaultTemperature = tenant.ConversationConfig.Temperature
+1 -125
View File
@@ -111,118 +111,6 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
return reqCtx, &request, nil
}
// detectAndApplyConfigChanges detects configuration changes and updates session if needed
// Returns true if any configuration changed
func (h *Handler) detectAndApplyConfigChanges(
reqCtx *qaRequestContext,
request *CreateKnowledgeQARequest,
) (bool, error) {
ctx := reqCtx.ctx
session := reqCtx.session
sessionID := reqCtx.sessionID
// Initialize AgentConfig if it doesn't exist
if session.AgentConfig == nil {
session.AgentConfig = &types.SessionAgentConfig{}
}
configChanged := false
// Check knowledge bases change
if hasArrayChanged(session.AgentConfig.KnowledgeBases, request.KnowledgeBaseIDs) {
logger.Infof(ctx, "Knowledge bases changed from %v to %v",
session.AgentConfig.KnowledgeBases, request.KnowledgeBaseIDs)
configChanged = true
}
// Check knowledge IDs change
if hasArrayChanged(session.AgentConfig.KnowledgeIDs, request.KnowledgeIds) {
logger.Infof(ctx, "Knowledge IDs changed from %v to %v",
session.AgentConfig.KnowledgeIDs, request.KnowledgeIds)
configChanged = true
}
// Check agent mode change
if request.AgentEnabled != session.AgentConfig.AgentModeEnabled {
logger.Infof(ctx, "Agent mode changed from %v to %v",
session.AgentConfig.AgentModeEnabled, request.AgentEnabled)
configChanged = true
}
// Check web search change
if request.WebSearchEnabled != session.AgentConfig.WebSearchEnabled {
logger.Infof(ctx, "Web search mode changed from %v to %v",
session.AgentConfig.WebSearchEnabled, request.WebSearchEnabled)
configChanged = true
}
// Resolve summary model ID
summaryModelID := reqCtx.summaryModelID
if summaryModelID == "" {
summaryModelID = session.SummaryModelID
}
if summaryModelID == "" {
if tenantInfo, ok := ctx.Value(types.TenantInfoContextKey).(*types.Tenant); ok && tenantInfo.ConversationConfig != nil {
summaryModelID = tenantInfo.ConversationConfig.SummaryModelID
}
}
if summaryModelID != session.SummaryModelID {
configChanged = true
}
// Apply changes if any
if configChanged {
logger.Warnf(ctx, "Configuration changed, clearing context for session: %s", sessionID)
// Clear LLM context
if err := h.sessionService.ClearContext(ctx, sessionID); err != nil {
logger.Errorf(ctx, "Failed to clear context for session %s: %v", sessionID, err)
}
// Delete temp KB state
if err := h.sessionService.DeleteWebSearchTempKBState(ctx, sessionID); err != nil {
logger.Errorf(ctx, "Failed to delete temp knowledge base for session %s: %v", sessionID, err)
}
// Update session config
session.AgentConfig.KnowledgeBases = secutils.SanitizeForLogArray(request.KnowledgeBaseIDs)
session.AgentConfig.KnowledgeIDs = secutils.SanitizeForLogArray(request.KnowledgeIds)
session.AgentConfig.AgentModeEnabled = request.AgentEnabled
session.AgentConfig.WebSearchEnabled = request.WebSearchEnabled
session.SummaryModelID = summaryModelID
// Persist changes
if err := h.sessionService.UpdateSession(ctx, session); err != nil {
logger.Errorf(ctx, "Failed to update session %s: %v", sessionID, err)
return false, errors.NewInternalServerError("Failed to update session configuration")
}
logger.Infof(ctx, "Session configuration updated successfully for session: %s", sessionID)
}
return configChanged, nil
}
// hasArrayChanged checks if two string arrays are different
func hasArrayChanged(current, new []string) bool {
if len(current) != len(new) {
return true
}
if len(current) == 0 && len(new) == 0 {
return false
}
currentMap := make(map[string]bool)
for _, v := range current {
currentMap[v] = true
}
for _, v := range new {
if !currentMap[v] {
return true
}
}
return false
}
// sseStreamContext holds the context for SSE streaming
type sseStreamContext struct {
eventBus *event.EventBus
@@ -388,12 +276,6 @@ func (h *Handler) AgentQA(c *gin.Context) {
return
}
// Detect and apply configuration changes
if _, err := h.detectAndApplyConfigChanges(reqCtx, request); err != nil {
c.Error(err)
return
}
// Determine if agent mode should be enabled
// Priority: customAgent.IsAgentMode() > request.AgentEnabled
agentModeEnabled := request.AgentEnabled
@@ -408,13 +290,7 @@ func (h *Handler) AgentQA(c *gin.Context) {
h.executeAgentModeQA(reqCtx)
} else {
logger.Infof(reqCtx.ctx, "Agent mode disabled, delegating to normal mode for session: %s", reqCtx.sessionID)
// Fallback to session's knowledge bases if not specified in request
if len(reqCtx.knowledgeBaseIDs) == 0 {
reqCtx.knowledgeBaseIDs = reqCtx.session.AgentConfig.KnowledgeBases
}
if len(reqCtx.knowledgeBaseIDs) == 0 && reqCtx.session.KnowledgeBaseID != "" {
reqCtx.knowledgeBaseIDs = []string{reqCtx.session.KnowledgeBaseID}
}
// Knowledge bases should be specified in request or from custom agent
h.executeNormalModeQA(reqCtx, false)
}
}
+48 -115
View File
@@ -425,7 +425,6 @@ type AgentConfigRequest struct {
Temperature float64 `json:"temperature"`
SystemPromptWebEnabled string `json:"system_prompt_web_enabled,omitempty"`
SystemPromptWebDisabled string `json:"system_prompt_web_disabled,omitempty"`
UseCustomPrompt *bool `json:"use_custom_system_prompt"`
}
// GetTenantAgentConfig godoc
@@ -497,8 +496,6 @@ func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) {
systemPromptWithoutWeb = agent.ProgressiveRAGSystemPromptWithoutWeb
}
useCustomPrompt := tenant.AgentConfig.UseCustomSystemPrompt
logger.Infof(ctx, "Retrieved tenant agent config successfully, Tenant ID: %d", tenant.ID)
c.JSON(http.StatusOK, gin.H{
"success": true,
@@ -509,7 +506,6 @@ func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) {
"temperature": tenant.AgentConfig.Temperature,
"system_prompt_web_enabled": systemPromptWithWeb,
"system_prompt_web_disabled": systemPromptWithoutWeb,
"use_custom_system_prompt": useCustomPrompt,
"available_tools": availableTools,
"available_placeholders": availablePlaceholders,
},
@@ -546,13 +542,8 @@ func (h *TenantHandler) updateTenantAgentConfigInternal(c *gin.Context) {
return
}
// Update agent configuration
useCustomPrompt := false
if tenant.AgentConfig != nil {
useCustomPrompt = tenant.AgentConfig.UseCustomSystemPrompt
}
if req.UseCustomPrompt != nil {
useCustomPrompt = *req.UseCustomPrompt
}
// Determine if using custom prompt based on whether custom prompts are set
useCustomPrompt := req.SystemPromptWebEnabled != "" || req.SystemPromptWebDisabled != ""
tenant.AgentConfig = &types.AgentConfig{
MaxIterations: req.MaxIterations,
@@ -610,6 +601,9 @@ func (h *TenantHandler) GetTenantKV(c *gin.Context) {
case "conversation-config":
h.GetTenantConversationConfig(c)
return
case "prompt-templates":
h.GetPromptTemplates(c)
return
default:
logger.Info(ctx, "KV key not supported", "key", key)
c.Error(errors.NewBadRequestError("unsupported key"))
@@ -726,25 +720,23 @@ func (h *TenantHandler) GetTenantWebSearchConfig(c *gin.Context) {
func (h *TenantHandler) buildDefaultConversationConfig() *types.ConversationConfig {
return &types.ConversationConfig{
Prompt: h.config.Conversation.Summary.Prompt,
ContextTemplate: h.config.Conversation.Summary.ContextTemplate,
UseCustomContextTemplate: true,
UseCustomSystemPrompt: true,
Temperature: h.config.Conversation.Summary.Temperature,
MaxCompletionTokens: h.config.Conversation.Summary.MaxCompletionTokens,
MaxRounds: h.config.Conversation.MaxRounds,
EmbeddingTopK: h.config.Conversation.EmbeddingTopK,
KeywordThreshold: h.config.Conversation.KeywordThreshold,
VectorThreshold: h.config.Conversation.VectorThreshold,
RerankTopK: h.config.Conversation.RerankTopK,
RerankThreshold: h.config.Conversation.RerankThreshold,
EnableRewrite: h.config.Conversation.EnableRewrite,
EnableQueryExpansion: h.config.Conversation.EnableQueryExpansion,
FallbackStrategy: h.config.Conversation.FallbackStrategy,
FallbackResponse: h.config.Conversation.FallbackResponse,
FallbackPrompt: h.config.Conversation.FallbackPrompt,
RewritePromptUser: h.config.Conversation.RewritePromptUser,
RewritePromptSystem: h.config.Conversation.RewritePromptSystem,
Prompt: h.config.Conversation.Summary.Prompt,
ContextTemplate: h.config.Conversation.Summary.ContextTemplate,
Temperature: h.config.Conversation.Summary.Temperature,
MaxCompletionTokens: h.config.Conversation.Summary.MaxCompletionTokens,
MaxRounds: h.config.Conversation.MaxRounds,
EmbeddingTopK: h.config.Conversation.EmbeddingTopK,
KeywordThreshold: h.config.Conversation.KeywordThreshold,
VectorThreshold: h.config.Conversation.VectorThreshold,
RerankTopK: h.config.Conversation.RerankTopK,
RerankThreshold: h.config.Conversation.RerankThreshold,
EnableRewrite: h.config.Conversation.EnableRewrite,
EnableQueryExpansion: h.config.Conversation.EnableQueryExpansion,
FallbackStrategy: h.config.Conversation.FallbackStrategy,
FallbackResponse: h.config.Conversation.FallbackResponse,
FallbackPrompt: h.config.Conversation.FallbackPrompt,
RewritePromptUser: h.config.Conversation.RewritePromptUser,
RewritePromptSystem: h.config.Conversation.RewritePromptSystem,
}
}
@@ -803,91 +795,8 @@ func (h *TenantHandler) GetTenantConversationConfig(c *gin.Context) {
// If tenant has no conversation config, return defaults from config.yaml
var response *types.ConversationConfig
if tc := tenant.ConversationConfig; tc == nil {
logger.Info(ctx, "Tenant has no conversation config, returning defaults")
response = h.buildDefaultConversationConfig()
} else {
logger.Infof(ctx, "Tenant has conversation config, merging with defaults, Tenant ID: %d", tenant.ID)
// Merge tenant config with defaults, so that newly added fields always have valid values
defaultCfg := h.buildDefaultConversationConfig()
// Prompt related
defaultCfg.UseCustomSystemPrompt = tc.UseCustomSystemPrompt
if !defaultCfg.UseCustomSystemPrompt && tc.Prompt != "" {
// Legacy configs without explicit flag
defaultCfg.UseCustomSystemPrompt = true
}
defaultCfg.UseCustomContextTemplate = tc.UseCustomContextTemplate
if !defaultCfg.UseCustomContextTemplate && tc.ContextTemplate != "" {
defaultCfg.UseCustomContextTemplate = true
}
if tc.Prompt != "" {
defaultCfg.Prompt = tc.Prompt
}
if tc.ContextTemplate != "" {
defaultCfg.ContextTemplate = tc.ContextTemplate
}
if tc.Temperature > 0 {
defaultCfg.Temperature = tc.Temperature
}
if tc.MaxCompletionTokens > 0 {
defaultCfg.MaxCompletionTokens = tc.MaxCompletionTokens
}
// Retrieval parameters
if tc.MaxRounds > 0 {
defaultCfg.MaxRounds = tc.MaxRounds
}
if tc.EmbeddingTopK > 0 {
defaultCfg.EmbeddingTopK = tc.EmbeddingTopK
}
if tc.KeywordThreshold > 0 {
defaultCfg.KeywordThreshold = tc.KeywordThreshold
}
if tc.VectorThreshold > 0 {
defaultCfg.VectorThreshold = tc.VectorThreshold
}
if tc.RerankTopK > 0 {
defaultCfg.RerankTopK = tc.RerankTopK
}
if tc.RerankThreshold > 0 {
defaultCfg.RerankThreshold = tc.RerankThreshold
}
// EnableRewrite 需要允许显式关闭,因此直接覆盖
defaultCfg.EnableRewrite = tc.EnableRewrite
// Query expansion toggle
defaultCfg.EnableQueryExpansion = tc.EnableQueryExpansion
// Model IDs
if tc.SummaryModelID != "" {
defaultCfg.SummaryModelID = tc.SummaryModelID
}
if tc.RerankModelID != "" {
defaultCfg.RerankModelID = tc.RerankModelID
}
// Fallback settings
if tc.FallbackStrategy != "" {
defaultCfg.FallbackStrategy = tc.FallbackStrategy
}
if tc.FallbackResponse != "" {
defaultCfg.FallbackResponse = tc.FallbackResponse
}
if tc.FallbackPrompt != "" {
defaultCfg.FallbackPrompt = tc.FallbackPrompt
}
// Rewrite prompts
if tc.RewritePromptSystem != "" {
defaultCfg.RewritePromptSystem = tc.RewritePromptSystem
}
if tc.RewritePromptUser != "" {
defaultCfg.RewritePromptUser = tc.RewritePromptUser
}
response = defaultCfg
}
logger.Info(ctx, "Tenant has no conversation config, returning defaults")
response = h.buildDefaultConversationConfig()
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": response,
@@ -943,3 +852,27 @@ func (h *TenantHandler) updateTenantConversationInternal(c *gin.Context) {
"message": "Conversation configuration updated successfully",
})
}
// GetPromptTemplates godoc
// @Summary 获取提示词模板
// @Description 获取系统配置的提示词模板列表
// @Tags 租户管理
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "提示词模板配置"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /tenants/kv/prompt-templates [get]
func (h *TenantHandler) GetPromptTemplates(c *gin.Context) {
// Return prompt templates from config.yaml
templates := h.config.PromptTemplates
if templates == nil {
templates = &config.PromptTemplatesConfig{}
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": templates,
})
}