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
@@ -27,10 +27,10 @@ func (r *customAgentRepository) CreateAgent(ctx context.Context, agent *types.Cu
return r.db.WithContext(ctx).Create(agent).Error
}
// GetAgentByID gets an agent by id
func (r *customAgentRepository) GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) {
// GetAgentByID gets an agent by id and tenant
func (r *customAgentRepository) GetAgentByID(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error) {
var agent types.CustomAgent
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&agent).Error; err != nil {
if err := r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).First(&agent).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrCustomAgentNotFound
}
@@ -2,6 +2,8 @@ package chatpipline
import (
"context"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/logger"
@@ -51,8 +53,11 @@ func prepareChatModel(ctx context.Context, modelService interfaces.ModelService,
// prepareMessagesWithHistory prepare complete messages including history
func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
// Replace placeholders in system prompt
systemPrompt := renderSystemPromptPlaceholders(chatManage.SummaryConfig.Prompt)
chatMessages := []chat.Message{
{Role: "system", Content: chatManage.SummaryConfig.Prompt},
{Role: "system", Content: systemPrompt},
}
chatHistory := chatManage.History
@@ -71,3 +76,18 @@ func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
return chatMessages
}
// renderSystemPromptPlaceholders replaces placeholders in system prompt
// Supported placeholders:
// - {{current_time}} -> current time in RFC3339 format
func renderSystemPromptPlaceholders(prompt string) string {
result := prompt
// Replace {{current_time}} placeholder
if strings.Contains(result, "{{current_time}}") {
currentTime := time.Now().Format(time.RFC3339)
result = strings.ReplaceAll(result, "{{current_time}}", currentTime)
}
return result
}
@@ -1,11 +1,9 @@
package chatpipline
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html/template"
"regexp"
"strings"
"time"
@@ -46,20 +44,6 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
passages[i] = getEnrichedPassageForChat(ctx, result)
}
// Parse the context template
tmpl, err := template.New("searchContent").Parse(chatManage.SummaryConfig.ContextTemplate)
if err != nil {
pipelineError(ctx, "IntoChatMessage", "parse_template", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return ErrTemplateParse.WithError(err)
}
// Prepare weekday names for template
weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}
var userContent bytes.Buffer
// 验证用户查询的安全性
safeQuery, isValid := secutils.ValidateInput(chatManage.Query)
if !isValid {
@@ -69,23 +53,27 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
return ErrTemplateExecute.WithError(fmt.Errorf("用户查询包含非法内容"))
}
// Execute template with context data
err = tmpl.Execute(&userContent, map[string]interface{}{
"Query": safeQuery, // User's original query
"Contexts": passages, // Extracted passages from search results
"CurrentTime": time.Now().Format("2006-01-02 15:04:05"), // Formatted current time
"CurrentWeek": weekdayName[time.Now().Weekday()], // Current weekday in Chinese
})
if err != nil {
pipelineError(ctx, "IntoChatMessage", "render_template", map[string]interface{}{
"session_id": chatManage.SessionID,
"error": err.Error(),
})
return ErrTemplateExecute.WithError(err)
// Prepare weekday names
weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}
// Build contexts string from passages
var contextsBuilder strings.Builder
for i, passage := range passages {
if i > 0 {
contextsBuilder.WriteString("\n\n")
}
contextsBuilder.WriteString(fmt.Sprintf("[%d] %s", i+1, passage))
}
// Replace placeholders in context template
userContent := chatManage.SummaryConfig.ContextTemplate
userContent = strings.ReplaceAll(userContent, "{{query}}", safeQuery)
userContent = strings.ReplaceAll(userContent, "{{contexts}}", contextsBuilder.String())
userContent = strings.ReplaceAll(userContent, "{{current_time}}", time.Now().Format("2006-01-02 15:04:05"))
userContent = strings.ReplaceAll(userContent, "{{current_week}}", weekdayName[time.Now().Weekday()])
// Set formatted content back to chat management
chatManage.UserContent = userContent.String()
chatManage.UserContent = userContent
pipelineInfo(ctx, "IntoChatMessage", "output", map[string]interface{}{
"session_id": chatManage.SessionID,
"user_content_len": len(chatManage.UserContent),
+132 -37
View File
@@ -16,7 +16,7 @@ import (
// Custom agent related errors
var (
ErrAgentNotFound = errors.New("agent not found")
ErrCannotModifyBuiltin = errors.New("cannot modify built-in agent")
ErrCannotModifyBuiltin = errors.New("cannot modify built-in agent basic info")
ErrCannotDeleteBuiltin = errors.New("cannot delete built-in agent")
ErrAgentNameRequired = errors.New("agent name is required")
)
@@ -96,15 +96,22 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*type
}
// Check if it's a built-in agent
if id == types.BuiltinAgentNormalID {
return types.GetBuiltinNormalAgent(tenantID), nil
}
if id == types.BuiltinAgentAgentID {
if id == types.BuiltinAgentNormalID || id == types.BuiltinAgentAgentID {
// Try to get from database first (for customized config)
agent, err := s.repo.GetAgentByID(ctx, id, tenantID)
if err == nil {
// Found in database, return with customized config
return agent, nil
}
// Not in database, return default built-in agent
if id == types.BuiltinAgentNormalID {
return types.GetBuiltinNormalAgent(tenantID), nil
}
return types.GetBuiltinAgentAgent(tenantID), nil
}
// Query from database
agent, err := s.repo.GetAgentByID(ctx, id)
agent, err := s.repo.GetAgentByID(ctx, id, tenantID)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return nil, ErrAgentNotFound
@@ -115,11 +122,6 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*type
return nil, err
}
// Verify tenant ownership
if agent.TenantID != tenantID {
return nil, ErrAgentNotFound
}
return agent, nil
}
@@ -130,11 +132,8 @@ func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAge
return nil, ErrInvalidTenantID
}
// Get built-in agents first
builtinAgents := types.GetBuiltinAgents(tenantID)
// Get custom agents from database
customAgents, err := s.repo.ListAgentsByTenantID(ctx, tenantID)
// Get all agents from database (including built-in agents with customized config)
allAgents, err := s.repo.ListAgentsByTenantID(ctx, tenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
@@ -142,10 +141,51 @@ func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAge
return nil, err
}
// Combine: built-in agents first, then custom agents
result := make([]*types.CustomAgent, 0, len(builtinAgents)+len(customAgents))
result = append(result, builtinAgents...)
result = append(result, customAgents...)
// Check if built-in agents exist in database
hasNormalBuiltin := false
hasAgentBuiltin := false
for _, agent := range allAgents {
if agent.ID == types.BuiltinAgentNormalID {
hasNormalBuiltin = true
}
if agent.ID == types.BuiltinAgentAgentID {
hasAgentBuiltin = true
}
}
// Build result: built-in agents first, then custom agents
result := make([]*types.CustomAgent, 0, len(allAgents)+2)
// Add built-in normal agent
if hasNormalBuiltin {
for _, agent := range allAgents {
if agent.ID == types.BuiltinAgentNormalID {
result = append(result, agent)
break
}
}
} else {
result = append(result, types.GetBuiltinNormalAgent(tenantID))
}
// Add built-in agent mode agent
if hasAgentBuiltin {
for _, agent := range allAgents {
if agent.ID == types.BuiltinAgentAgentID {
result = append(result, agent)
break
}
}
} else {
result = append(result, types.GetBuiltinAgentAgent(tenantID))
}
// Add custom agents
for _, agent := range allAgents {
if agent.ID != types.BuiltinAgentNormalID && agent.ID != types.BuiltinAgentAgentID {
result = append(result, agent)
}
}
return result, nil
}
@@ -157,19 +197,20 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo
return nil, errors.New("agent ID cannot be empty")
}
// Cannot modify built-in agents
if agent.ID == types.BuiltinAgentNormalID || agent.ID == types.BuiltinAgentAgentID {
return nil, ErrCannotModifyBuiltin
}
// Get tenant ID from context
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return nil, ErrInvalidTenantID
}
// Handle built-in agents specially
isBuiltinAgent := agent.ID == types.BuiltinAgentNormalID || agent.ID == types.BuiltinAgentAgentID
if isBuiltinAgent {
return s.updateBuiltinAgent(ctx, agent, tenantID)
}
// Get existing agent
existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID)
existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID, tenantID)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return nil, ErrAgentNotFound
@@ -177,11 +218,6 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo
return nil, err
}
// Verify tenant ownership
if existingAgent.TenantID != tenantID {
return nil, ErrAgentNotFound
}
// Cannot modify built-in status
if existingAgent.IsBuiltin {
return nil, ErrCannotModifyBuiltin
@@ -216,6 +252,70 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo
return existingAgent, nil
}
// updateBuiltinAgent updates a built-in agent's configuration (but not basic info)
func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *types.CustomAgent, tenantID uint64) (*types.CustomAgent, error) {
// Get the default built-in agent
var defaultAgent *types.CustomAgent
if agent.ID == types.BuiltinAgentNormalID {
defaultAgent = types.GetBuiltinNormalAgent(tenantID)
} else {
defaultAgent = types.GetBuiltinAgentAgent(tenantID)
}
// Try to get existing customized config from database
existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID, tenantID)
if err != nil && !errors.Is(err, repository.ErrCustomAgentNotFound) {
return nil, err
}
if existingAgent != nil {
// Update existing record - only update config, keep basic info unchanged
existingAgent.Config = agent.Config
existingAgent.UpdatedAt = time.Now()
existingAgent.EnsureDefaults()
logger.Infof(ctx, "Updating built-in agent config, ID: %s", agent.ID)
if err := s.repo.UpdateAgent(ctx, existingAgent); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": agent.ID,
})
return nil, err
}
logger.Infof(ctx, "Built-in agent config updated successfully, ID: %s", agent.ID)
return existingAgent, nil
}
// Create new record for built-in agent with customized config
newAgent := &types.CustomAgent{
ID: defaultAgent.ID,
Name: defaultAgent.Name,
Description: defaultAgent.Description,
Avatar: defaultAgent.Avatar,
IsBuiltin: true,
Type: defaultAgent.Type,
TenantID: tenantID,
Config: agent.Config,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
newAgent.EnsureDefaults()
logger.Infof(ctx, "Creating built-in agent config record, ID: %s, tenant ID: %d", agent.ID, tenantID)
if err := s.repo.CreateAgent(ctx, newAgent); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": agent.ID,
"tenant_id": tenantID,
})
return nil, err
}
logger.Infof(ctx, "Built-in agent config record created successfully, ID: %s", agent.ID)
return newAgent, nil
}
// DeleteAgent deletes an agent
func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {
if id == "" {
@@ -235,7 +335,7 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {
}
// Get existing agent to verify ownership
existingAgent, err := s.repo.GetAgentByID(ctx, id)
existingAgent, err := s.repo.GetAgentByID(ctx, id, tenantID)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return ErrAgentNotFound
@@ -243,11 +343,6 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {
return err
}
// Verify tenant ownership
if existingAgent.TenantID != tenantID {
return ErrAgentNotFound
}
// Cannot delete built-in agents
if existingAgent.IsBuiltin {
return ErrCannotDeleteBuiltin
-42
View File
@@ -3403,47 +3403,6 @@ func (s *knowledgeService) GetFAQEntry(ctx context.Context,
return entry, nil
}
// GetFAQEntry retrieves a single FAQ entry by ID.
func (s *knowledgeService) GetFAQEntry(ctx context.Context,
kbID string, entryID string,
) (*types.FAQEntry, error) {
if entryID == "" {
return nil, werrors.NewBadRequestError("条目ID不能为空")
}
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
if err != nil {
return nil, err
}
kb.EnsureDefaults()
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// 获取chunk
chunk, err := s.chunkService.GetChunkByID(ctx, entryID)
if err != nil {
return nil, err
}
// 验证chunk属于当前知识库
if chunk.KnowledgeBaseID != kb.ID || chunk.TenantID != tenantID {
return nil, werrors.NewNotFoundError("FAQ条目不存在")
}
// 验证是FAQ类型
if chunk.ChunkType != types.ChunkTypeFAQ {
return nil, werrors.NewNotFoundError("FAQ条目不存在")
}
// 转换为FAQEntry返回
entry, err := s.chunkToFAQEntry(chunk, kb)
if err != nil {
return nil, err
}
return entry, nil
}
// UpdateFAQEntry updates a single FAQ entry.
func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,
kbID string, entryID string, payload *types.FAQEntryPayload,
@@ -5901,4 +5860,3 @@ func (s *knowledgeService) SearchKnowledge(ctx context.Context, keyword string,
}
return s.repo.SearchKnowledge(ctx, tenantID, keyword, offset, limit)
}
+155 -242
View File
@@ -87,8 +87,7 @@ func (s *sessionService) CreateSession(ctx context.Context, session *types.Sessi
return nil, errors.New("tenant ID is required")
}
logger.Infof(ctx, "Creating session, tenant ID: %d, model ID: %s, knowledge base ID: %s",
session.TenantID, session.SummaryModelID, session.KnowledgeBaseID)
logger.Infof(ctx, "Creating session, tenant ID: %d", session.TenantID)
// Create session in repository
createdSession, err := s.sessionRepo.Create(ctx, session)
@@ -259,31 +258,29 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
return "", errors.New("no user message found")
}
// Get chat model, use default if SummaryModelID is empty
modelID := session.SummaryModelID
if modelID == "" {
// Try to get an available KnowledgeQA model
models, err := s.modelService.ListModels(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return "", fmt.Errorf("failed to list models: %w", err)
// Get chat model, find an available model
modelID := ""
// Try to get an available KnowledgeQA model
models, err := s.modelService.ListModels(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return "", fmt.Errorf("failed to list models: %w", err)
}
// Find first available KnowledgeQA model
for _, model := range models {
if model == nil {
continue
}
// Find first available KnowledgeQA model
for _, model := range models {
if model == nil {
continue
}
if model.Type == types.ModelTypeKnowledgeQA {
modelID = model.ID
logger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID)
break
}
}
if modelID == "" {
logger.Error(ctx, "No KnowledgeQA model found")
return "", errors.New("no KnowledgeQA model available for title generation")
modelID = model.ID
logger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID)
break
}
}
if modelID == "" {
logger.Error(ctx, "No KnowledgeQA model found")
return "", errors.New("no KnowledgeQA model available for title generation")
}
chatModel, err := s.modelService.GetChatModel(ctx, modelID)
if err != nil {
@@ -413,16 +410,6 @@ func (s *sessionService) KnowledgeQA(
webSearchEnabled,
)
// If no knowledge base IDs provided, fall back to session's default
if len(knowledgeBaseIDs) == 0 {
if session.KnowledgeBaseID != "" {
knowledgeBaseIDs = []string{session.KnowledgeBaseID}
logger.Infof(ctx, "No knowledge base IDs provided, using session default: %s", session.KnowledgeBaseID)
} else {
logger.Warnf(ctx, "Session has no associated knowledge base, session ID: %s", session.ID)
}
}
// Merge custom agent's configured knowledge bases
if customAgent != nil && len(customAgent.Config.KnowledgeBases) > 0 {
// Create a set of existing knowledge base IDs to avoid duplicates
@@ -447,83 +434,28 @@ func (s *sessionService) KnowledgeQA(
return err
}
// Initialize default values from config.yaml
rewritePromptSystem := s.cfg.Conversation.RewritePromptSystem
rewritePromptUser := s.cfg.Conversation.RewritePromptUser
var tenantConv *types.ConversationConfig
if tc, err := getTenantConversationConfig(ctx); err == nil {
tenantConv = tc
} else {
logger.Warnf(ctx, "Failed to load tenant conversation config, tenant ID: %d, error: %v", session.TenantID, err)
}
vectorThreshold := s.cfg.Conversation.VectorThreshold
keywordThreshold := s.cfg.Conversation.KeywordThreshold
embeddingTopK := s.cfg.Conversation.EmbeddingTopK
rerankTopK := s.cfg.Conversation.RerankTopK
rerankThreshold := s.cfg.Conversation.RerankThreshold
maxRounds := s.cfg.Conversation.MaxRounds
fallbackStrategy := types.FallbackStrategy(s.cfg.Conversation.FallbackStrategy)
fallbackResponse := s.cfg.Conversation.FallbackResponse
fallbackPrompt := s.cfg.Conversation.FallbackPrompt
enableRewrite := s.cfg.Conversation.EnableRewrite
enableQueryExpansion := s.cfg.Conversation.EnableQueryExpansion
rerankModelID := ""
vectorThreshold := session.VectorThreshold
keywordThreshold := session.KeywordThreshold
embeddingTopK := session.EmbeddingTopK
rerankModelID := session.RerankModelID
rerankTopK := session.RerankTopK
rerankThreshold := session.RerankThreshold
maxRounds := session.MaxRounds
fallbackStrategy := session.FallbackStrategy
fallbackResponse := session.FallbackResponse
fallbackPrompt := ""
enableRewrite := session.EnableRewrite
enableQueryExpansion := true
summaryParams := session.SummaryParameters
if summaryParams == nil {
summaryParams = &types.SummaryConfig{}
}
summaryConfig := types.SummaryConfig{
MaxTokens: summaryParams.MaxTokens,
RepeatPenalty: summaryParams.RepeatPenalty,
TopK: summaryParams.TopK,
TopP: summaryParams.TopP,
FrequencyPenalty: summaryParams.FrequencyPenalty,
PresencePenalty: summaryParams.PresencePenalty,
Prompt: summaryParams.Prompt,
ContextTemplate: summaryParams.ContextTemplate,
Temperature: summaryParams.Temperature,
Seed: summaryParams.Seed,
NoMatchPrefix: summaryParams.NoMatchPrefix,
MaxCompletionTokens: summaryParams.MaxCompletionTokens,
}
if tenantConv != nil {
vectorThreshold = tenantConv.VectorThreshold
keywordThreshold = tenantConv.KeywordThreshold
embeddingTopK = tenantConv.EmbeddingTopK
rerankModelID = tenantConv.RerankModelID
rerankTopK = tenantConv.RerankTopK
rerankThreshold = tenantConv.RerankThreshold
maxRounds = tenantConv.MaxRounds
if tenantConv.FallbackStrategy != "" {
fallbackStrategy = types.FallbackStrategy(tenantConv.FallbackStrategy)
}
fallbackResponse = tenantConv.FallbackResponse
if tenantConv.FallbackPrompt != "" {
fallbackPrompt = tenantConv.FallbackPrompt
}
enableRewrite = tenantConv.EnableRewrite
enableQueryExpansion = tenantConv.EnableQueryExpansion
if tenantConv.MaxCompletionTokens != 0 {
summaryConfig.MaxCompletionTokens = tenantConv.MaxCompletionTokens
}
if tenantConv.Prompt != "" {
summaryConfig.Prompt = tenantConv.Prompt
}
if tenantConv.ContextTemplate != "" {
summaryConfig.ContextTemplate = tenantConv.ContextTemplate
}
if tenantConv.Temperature != 0 {
summaryConfig.Temperature = tenantConv.Temperature
}
if tenantConv.RewritePromptSystem != "" {
rewritePromptSystem = tenantConv.RewritePromptSystem
}
if tenantConv.RewritePromptUser != "" {
rewritePromptUser = tenantConv.RewritePromptUser
}
Prompt: s.cfg.Conversation.Summary.Prompt,
ContextTemplate: s.cfg.Conversation.Summary.ContextTemplate,
Temperature: s.cfg.Conversation.Summary.Temperature,
NoMatchPrefix: s.cfg.Conversation.Summary.NoMatchPrefix,
MaxCompletionTokens: s.cfg.Conversation.Summary.MaxCompletionTokens,
}
// Set default fallback strategy if not set
@@ -533,26 +465,75 @@ func (s *sessionService) KnowledgeQA(
}
// Apply custom agent configuration if provided
multiTurnEnabled := true // Default: enable multi-turn
if customAgent != nil {
// Override system prompt with customAgent's SystemPrompt
// Ensure defaults are set
customAgent.EnsureDefaults()
// Override system prompt
if customAgent.Config.SystemPrompt != "" {
summaryConfig.Prompt = customAgent.Config.SystemPrompt
logger.Infof(ctx, "Using custom agent's system_prompt")
}
// Override temperature with customAgent's Temperature
// Override context template
if customAgent.Config.ContextTemplate != "" {
summaryConfig.ContextTemplate = customAgent.Config.ContextTemplate
logger.Infof(ctx, "Using custom agent's context_template")
}
// Override temperature
if customAgent.Config.Temperature > 0 {
summaryConfig.Temperature = customAgent.Config.Temperature
logger.Infof(ctx, "Using custom agent's temperature: %f", customAgent.Config.Temperature)
}
// Override maxRounds with customAgent's HistoryTurns
// Override max completion tokens
if customAgent.Config.MaxCompletionTokens > 0 {
summaryConfig.MaxCompletionTokens = customAgent.Config.MaxCompletionTokens
logger.Infof(ctx, "Using custom agent's max_completion_tokens: %d", customAgent.Config.MaxCompletionTokens)
}
// Override retrieval strategy settings
if customAgent.Config.EmbeddingTopK > 0 {
embeddingTopK = customAgent.Config.EmbeddingTopK
}
if customAgent.Config.KeywordThreshold > 0 {
keywordThreshold = customAgent.Config.KeywordThreshold
}
if customAgent.Config.VectorThreshold > 0 {
vectorThreshold = customAgent.Config.VectorThreshold
}
if customAgent.Config.RerankTopK > 0 {
rerankTopK = customAgent.Config.RerankTopK
}
if customAgent.Config.RerankThreshold > 0 {
rerankThreshold = customAgent.Config.RerankThreshold
}
if customAgent.Config.RerankModelID != "" {
rerankModelID = customAgent.Config.RerankModelID
}
// Override rewrite settings
enableRewrite = customAgent.Config.EnableRewrite
enableQueryExpansion = customAgent.Config.EnableQueryExpansion
if customAgent.Config.RewritePromptSystem != "" {
rewritePromptSystem = customAgent.Config.RewritePromptSystem
}
if customAgent.Config.RewritePromptUser != "" {
rewritePromptUser = customAgent.Config.RewritePromptUser
}
// Override fallback settings
if customAgent.Config.FallbackStrategy != "" {
fallbackStrategy = types.FallbackStrategy(customAgent.Config.FallbackStrategy)
}
if customAgent.Config.FallbackResponse != "" {
fallbackResponse = customAgent.Config.FallbackResponse
}
if customAgent.Config.FallbackPrompt != "" {
fallbackPrompt = customAgent.Config.FallbackPrompt
}
// Override history turns
if customAgent.Config.HistoryTurns > 0 {
maxRounds = customAgent.Config.HistoryTurns
logger.Infof(ctx, "Using custom agent's history_turns: %d", maxRounds)
}
// Check if multi-turn is disabled
multiTurnEnabled = customAgent.Config.MultiTurnEnabled
if !multiTurnEnabled {
if !customAgent.Config.MultiTurnEnabled {
maxRounds = 0 // Disable history
logger.Infof(ctx, "Multi-turn disabled by custom agent, clearing history")
}
@@ -625,8 +606,7 @@ func (s *sessionService) KnowledgeQA(
err = s.KnowledgeQAByEvent(ctx, chatManage, pipeline)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": session.ID,
"knowledge_base_id": session.KnowledgeBaseID,
"session_id": session.ID,
})
return err
}
@@ -703,10 +683,6 @@ func (s *sessionService) selectChatModelID(
knowledgeIDs []string,
) (string, error) {
// First, check if session has a SummaryModelID and if it's a Remote model
if session.SummaryModelID != "" {
return session.SummaryModelID, nil
}
// If no knowledge base IDs but have knowledge IDs, derive KB IDs from knowledge IDs
if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) > 0 {
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
@@ -728,7 +704,7 @@ func (s *sessionService) selectChatModelID(
len(knowledgeBaseIDs), len(knowledgeIDs))
}
}
// If no Remote model found from session, check knowledge bases for Remote models
// Check knowledge bases for models
if len(knowledgeBaseIDs) > 0 {
// Try to find a knowledge base with Remote model
for _, kbID := range knowledgeBaseIDs {
@@ -746,13 +722,7 @@ func (s *sessionService) selectChatModelID(
}
}
// If still no Remote model found, use session's SummaryModelID if available
if session.SummaryModelID != "" {
logger.Infof(ctx, "No Remote model found, using session's summary model: %s", session.SummaryModelID)
return session.SummaryModelID, nil
}
// If still empty, use first knowledge base's model
// If no Remote model found, use first knowledge base's model
kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, knowledgeBaseIDs[0])
if err != nil {
logger.Errorf(ctx, "Failed to get knowledge base for model ID: %v", err)
@@ -766,22 +736,24 @@ func (s *sessionService) selectChatModelID(
kb.SummaryModelID,
)
return kb.SummaryModelID, nil
} else {
logger.Errorf(ctx, "Knowledge base %s has no summary model ID", knowledgeBaseIDs[0])
return "", fmt.Errorf("knowledge base %s has no summary model configured", knowledgeBaseIDs[0])
}
}
// No knowledge bases - use session's SummaryModelID if available
if session.SummaryModelID != "" {
logger.Infof(ctx, "No knowledge bases, using session's summary model: %s", session.SummaryModelID)
return session.SummaryModelID, nil
// No knowledge bases - try to find any available chat model
models, err := s.modelService.ListModels(ctx)
if err != nil {
logger.Errorf(ctx, "Failed to list models: %v", err)
return "", fmt.Errorf("failed to list models: %w", err)
}
for _, model := range models {
if model != nil && model.Type == types.ModelTypeKnowledgeQA {
logger.Infof(ctx, "Using first available KnowledgeQA model: %s", model.ID)
return model.ID, nil
}
}
logger.Error(ctx, "No chat model ID available")
return "", errors.New(
"no chat model ID available: session has no SummaryModelID and no knowledge bases configured",
)
return "", errors.New("no chat model ID available: no knowledge bases configured and no available models")
}
// buildSearchTargets computes the unified search targets from knowledgeBaseIDs and knowledgeIDs
@@ -1049,18 +1021,20 @@ func (s *sessionService) AgentQA(
sessionID, tenantID, query, string(sessionJSON))
// Build effective agent configuration by merging session and tenant configs
// Session-level config: Enabled, KnowledgeBases (stored in session.AgentConfig)
// Tenant-level config: MaxIterations, Temperature, Models, Tools, etc. (from tenant.AgentConfig)
// All config now comes from customAgent parameter
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
// Check if agent is enabled at session level
if session.AgentConfig == nil {
logger.Warnf(ctx, "Agent config not found for session: %s", sessionID)
return errors.New("agent config not found for session")
// customAgent is required for AgentQA
if customAgent == nil {
logger.Warnf(ctx, "Custom agent not provided for session: %s", sessionID)
return errors.New("custom agent configuration is required for agent QA")
}
// Check if tenant has agent configuration
// Ensure defaults are set
customAgent.EnsureDefaults()
// Check if tenant has agent configuration (for defaults)
if tenantInfo.AgentConfig == nil {
tenantInfo.AgentConfig = &types.AgentConfig{
MaxIterations: agent.DefaultAgentMaxIterations,
@@ -1073,76 +1047,35 @@ func (s *sessionService) AgentQA(
}
}
// Create runtime AgentConfig
// Priority: CustomAgent config > Tenant config > Defaults
// Session config provides KnowledgeBases and KnowledgeIDs
var agentConfig *types.AgentConfig
if customAgent != nil && customAgent.ID != types.BuiltinAgentNormalID && customAgent.ID != types.BuiltinAgentAgentID {
// Use custom agent configuration
logger.Infof(ctx, "Using custom agent configuration, agent ID: %s, name: %s", customAgent.ID, customAgent.Name)
customAgent.EnsureDefaults()
agentConfig = &types.AgentConfig{
MaxIterations: customAgent.Config.MaxIterations,
ReflectionEnabled: customAgent.Config.ReflectionEnabled,
Temperature: customAgent.Config.Temperature,
WebSearchEnabled: customAgent.Config.WebSearchEnabled,
WebSearchMaxResults: customAgent.Config.WebSearchMaxResults,
MultiTurnEnabled: customAgent.Config.MultiTurnEnabled,
HistoryTurns: customAgent.Config.HistoryTurns,
}
// Use custom agent's allowed tools if specified, otherwise use defaults
if len(customAgent.Config.AllowedTools) > 0 {
agentConfig.AllowedTools = customAgent.Config.AllowedTools
} else {
agentConfig.AllowedTools = tools.DefaultAllowedTools()
}
// Use custom agent's system prompt if specified
if customAgent.Config.SystemPrompt != "" {
agentConfig.UseCustomSystemPrompt = true
agentConfig.SystemPromptWebEnabled = customAgent.Config.SystemPrompt
agentConfig.SystemPromptWebDisabled = customAgent.Config.SystemPrompt
}
// Use custom agent's knowledge bases if specified, otherwise use session's
if len(customAgent.Config.KnowledgeBases) > 0 {
agentConfig.KnowledgeBases = customAgent.Config.KnowledgeBases
} else {
agentConfig.KnowledgeBases = session.AgentConfig.KnowledgeBases
}
agentConfig.KnowledgeIDs = session.AgentConfig.KnowledgeIDs
// Override summary model if custom agent specifies one
if customAgent.Config.ModelID != "" {
session.SummaryModelID = customAgent.Config.ModelID
}
logger.Infof(ctx, "Custom agent config applied: MaxIterations=%d, Temperature=%.2f, AllowedTools=%v, WebSearchEnabled=%v",
agentConfig.MaxIterations, agentConfig.Temperature, agentConfig.AllowedTools, agentConfig.WebSearchEnabled)
} else {
// Use tenant configuration (default behavior)
agentConfig = &types.AgentConfig{
MaxIterations: tenantInfo.AgentConfig.MaxIterations,
ReflectionEnabled: tenantInfo.AgentConfig.ReflectionEnabled,
AllowedTools: tools.DefaultAllowedTools(),
Temperature: tenantInfo.AgentConfig.Temperature,
KnowledgeBases: session.AgentConfig.KnowledgeBases, // Use session's knowledge bases
KnowledgeIDs: session.AgentConfig.KnowledgeIDs, // Use session's knowledge IDs (individual documents)
WebSearchEnabled: session.AgentConfig.WebSearchEnabled, // Web search enabled from session config
MultiTurnEnabled: true, // Default: enable multi-turn
HistoryTurns: 5, // Default: keep 5 turns
}
agentConfig.UseCustomSystemPrompt = tenantInfo.AgentConfig.UseCustomSystemPrompt
if agentConfig.UseCustomSystemPrompt {
agentConfig.SystemPromptWebEnabled = tenantInfo.AgentConfig.ResolveSystemPrompt(true)
agentConfig.SystemPromptWebDisabled = tenantInfo.AgentConfig.ResolveSystemPrompt(false)
}
// Create runtime AgentConfig from customAgent
agentConfig := &types.AgentConfig{
MaxIterations: customAgent.Config.MaxIterations,
ReflectionEnabled: customAgent.Config.ReflectionEnabled,
Temperature: customAgent.Config.Temperature,
WebSearchEnabled: customAgent.Config.WebSearchEnabled,
WebSearchMaxResults: customAgent.Config.WebSearchMaxResults,
MultiTurnEnabled: customAgent.Config.MultiTurnEnabled,
HistoryTurns: customAgent.Config.HistoryTurns,
KnowledgeBases: customAgent.Config.KnowledgeBases,
}
// Use custom agent's allowed tools if specified, otherwise use defaults
if len(customAgent.Config.AllowedTools) > 0 {
agentConfig.AllowedTools = customAgent.Config.AllowedTools
} else {
agentConfig.AllowedTools = tools.DefaultAllowedTools()
}
// Use custom agent's system prompt if specified
if customAgent.Config.SystemPrompt != "" {
agentConfig.UseCustomSystemPrompt = true
agentConfig.SystemPromptWebEnabled = customAgent.Config.SystemPrompt
agentConfig.SystemPromptWebDisabled = customAgent.Config.SystemPrompt
}
logger.Infof(ctx, "Custom agent config applied: MaxIterations=%d, Temperature=%.2f, AllowedTools=%v, WebSearchEnabled=%v",
agentConfig.MaxIterations, agentConfig.Temperature, agentConfig.AllowedTools, agentConfig.WebSearchEnabled)
// Set web search max results from tenant config if not set (default: 5)
if agentConfig.WebSearchMaxResults == 0 {
agentConfig.WebSearchMaxResults = 5
@@ -1153,31 +1086,13 @@ func (s *sessionService) AgentQA(
logger.Infof(ctx, "Merged agent config from tenant %d and session %s", tenantInfo.ID, sessionID)
// Log knowledge IDs if present
if len(agentConfig.KnowledgeIDs) > 0 {
logger.Infof(ctx, "Agent configured with %d individual knowledge ID(s): %v",
len(agentConfig.KnowledgeIDs), agentConfig.KnowledgeIDs)
}
// Determine knowledge bases for agent
// Priority: Session.AgentConfig.KnowledgeBases > Session.KnowledgeBaseID > All tenant knowledge bases
// Exception: If KnowledgeIDs are specified, don't auto-add all KBs (let buildSearchTargets handle it)
if len(agentConfig.KnowledgeBases) == 0 && len(agentConfig.KnowledgeIDs) == 0 {
if session.KnowledgeBaseID != "" {
// Use session's knowledge base as fallback
agentConfig.KnowledgeBases = []string{session.KnowledgeBaseID}
logger.Infof(ctx, "Using session's knowledge base for agent: %s", session.KnowledgeBaseID)
} else {
// Allow running without knowledge bases (Pure Agent mode)
logger.Infof(ctx, "No knowledge bases specified for agent, running in pure agent mode")
}
} else if len(agentConfig.KnowledgeIDs) > 0 && len(agentConfig.KnowledgeBases) == 0 {
// User specified individual files but no KBs - don't auto-add all KBs
logger.Infof(ctx, "Agent configured with %d individual knowledge ID(s), no KB auto-expansion",
len(agentConfig.KnowledgeIDs))
} else {
// Log knowledge bases if present
if len(agentConfig.KnowledgeBases) > 0 {
logger.Infof(ctx, "Agent configured with %d knowledge base(s): %v",
len(agentConfig.KnowledgeBases), agentConfig.KnowledgeBases)
} else {
// Allow running without knowledge bases (Pure Agent mode)
logger.Infof(ctx, "No knowledge bases specified for agent, running in pure agent mode")
}
// Build search targets for agent (pre-compute once to avoid repeated queries)
@@ -1189,7 +1104,8 @@ func (s *sessionService) AgentQA(
agentConfig.SearchTargets = searchTargets
logger.Infof(ctx, "Agent search targets built: %d targets", len(searchTargets))
summaryModelID := session.SummaryModelID
// Get summary model from custom agent config or tenant config
summaryModelID := customAgent.Config.ModelID
if summaryModelID == "" && tenantInfo.ConversationConfig != nil {
summaryModelID = tenantInfo.ConversationConfig.SummaryModelID
}
@@ -1204,7 +1120,8 @@ func (s *sessionService) AgentQA(
return fmt.Errorf("failed to get chat model: %w", err)
}
rerankModelID := session.RerankModelID
// Get rerank model from custom agent config or tenant config
rerankModelID := customAgent.Config.RerankModelID
if rerankModelID == "" && tenantInfo.ConversationConfig != nil {
rerankModelID = tenantInfo.ConversationConfig.RerankModelID
}
@@ -1296,13 +1213,9 @@ func (s *sessionService) getContextManagerForSession(
) interfaces.ContextManager {
// Get tenant to access global context configuration
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
// Determine which context config to use: session-specific or tenant-level
// Determine which context config to use: tenant-level or default
var contextConfig *types.ContextConfig
if session.ContextConfig != nil {
// Use session-specific configuration
contextConfig = session.ContextConfig
logger.Infof(ctx, "Using session-specific context config for session %s", session.ID)
} else if tenant.ContextConfig != nil {
if tenant != nil && tenant.ContextConfig != nil {
// Use tenant-level configuration
contextConfig = tenant.ContextConfig
logger.Infof(ctx, "Using tenant-level context config for session %s", session.ID)
+91 -10
View File
@@ -3,6 +3,7 @@ package config
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"time"
@@ -10,20 +11,22 @@ import (
"github.com/Tencent/WeKnora/internal/types"
"github.com/go-viper/mapstructure/v2"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)
// Config 应用程序总配置
type Config struct {
Conversation *ConversationConfig `yaml:"conversation" json:"conversation"`
Server *ServerConfig `yaml:"server" json:"server"`
KnowledgeBase *KnowledgeBaseConfig `yaml:"knowledge_base" json:"knowledge_base"`
Tenant *TenantConfig `yaml:"tenant" json:"tenant"`
Models []ModelConfig `yaml:"models" json:"models"`
VectorDatabase *VectorDatabaseConfig `yaml:"vector_database" json:"vector_database"`
DocReader *DocReaderConfig `yaml:"docreader" json:"docreader"`
StreamManager *StreamManagerConfig `yaml:"stream_manager" json:"stream_manager"`
ExtractManager *ExtractManagerConfig `yaml:"extract" json:"extract"`
WebSearch *WebSearchConfig `yaml:"web_search" json:"web_search"`
Conversation *ConversationConfig `yaml:"conversation" json:"conversation"`
Server *ServerConfig `yaml:"server" json:"server"`
KnowledgeBase *KnowledgeBaseConfig `yaml:"knowledge_base" json:"knowledge_base"`
Tenant *TenantConfig `yaml:"tenant" json:"tenant"`
Models []ModelConfig `yaml:"models" json:"models"`
VectorDatabase *VectorDatabaseConfig `yaml:"vector_database" json:"vector_database"`
DocReader *DocReaderConfig `yaml:"docreader" json:"docreader"`
StreamManager *StreamManagerConfig `yaml:"stream_manager" json:"stream_manager"`
ExtractManager *ExtractManagerConfig `yaml:"extract" json:"extract"`
WebSearch *WebSearchConfig `yaml:"web_search" json:"web_search"`
PromptTemplates *PromptTemplatesConfig `yaml:"prompt_templates" json:"prompt_templates"`
}
type DocReaderConfig struct {
@@ -108,6 +111,25 @@ type TenantConfig struct {
EnableCrossTenantAccess bool `yaml:"enable_cross_tenant_access" json:"enable_cross_tenant_access"`
}
// PromptTemplate 提示词模板
type PromptTemplate struct {
ID string `yaml:"id" json:"id"`
Name string `yaml:"name" json:"name"`
Description string `yaml:"description" json:"description"`
Content string `yaml:"content" json:"content"`
HasKnowledgeBase bool `yaml:"has_knowledge_base" json:"has_knowledge_base,omitempty"`
HasWebSearch bool `yaml:"has_web_search" json:"has_web_search,omitempty"`
}
// PromptTemplatesConfig 提示词模板配置
type PromptTemplatesConfig struct {
SystemPrompt []PromptTemplate `yaml:"system_prompt" json:"system_prompt"`
ContextTemplate []PromptTemplate `yaml:"context_template" json:"context_template"`
RewriteSystem []PromptTemplate `yaml:"rewrite_system" json:"rewrite_system"`
RewriteUser []PromptTemplate `yaml:"rewrite_user" json:"rewrite_user"`
Fallback []PromptTemplate `yaml:"fallback" json:"fallback"`
}
// ModelConfig 模型配置
type ModelConfig struct {
Type string `yaml:"type" json:"type"`
@@ -192,9 +214,68 @@ func LoadConfig() (*Config, error) {
return nil, fmt.Errorf("unable to decode config into struct: %w", err)
}
fmt.Printf("Using configuration file: %s\n", viper.ConfigFileUsed())
// 加载提示词模板(从目录或配置文件)
configDir := filepath.Dir(viper.ConfigFileUsed())
promptTemplates, err := loadPromptTemplates(configDir)
if err != nil {
fmt.Printf("Warning: failed to load prompt templates from directory: %v\n", err)
// 如果目录加载失败,使用配置文件中的模板(如果有)
} else if promptTemplates != nil {
cfg.PromptTemplates = promptTemplates
}
return &cfg, nil
}
// promptTemplateFile 用于解析模板文件
type promptTemplateFile struct {
Templates []PromptTemplate `yaml:"templates"`
}
// loadPromptTemplates 从目录加载提示词模板
func loadPromptTemplates(configDir string) (*PromptTemplatesConfig, error) {
templatesDir := filepath.Join(configDir, "prompt_templates")
// 检查目录是否存在
if _, err := os.Stat(templatesDir); os.IsNotExist(err) {
return nil, nil // 目录不存在,返回nil让调用者使用配置文件中的模板
}
config := &PromptTemplatesConfig{}
// 定义模板文件映射
templateFiles := map[string]*[]PromptTemplate{
"system_prompt.yaml": &config.SystemPrompt,
"context_template.yaml": &config.ContextTemplate,
"rewrite_system.yaml": &config.RewriteSystem,
"rewrite_user.yaml": &config.RewriteUser,
"fallback.yaml": &config.Fallback,
}
// 加载每个模板文件
for filename, target := range templateFiles {
filePath := filepath.Join(templatesDir, filename)
if _, err := os.Stat(filePath); os.IsNotExist(err) {
continue // 文件不存在,跳过
}
data, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("failed to read %s: %w", filename, err)
}
var file promptTemplateFile
if err := yaml.Unmarshal(data, &file); err != nil {
return nil, fmt.Errorf("failed to parse %s: %w", filename, err)
}
*target = file.Templates
}
return config, nil
}
// WebSearchConfig represents the web search configuration
type WebSearchConfig struct {
Providers []WebSearchProviderConfig `yaml:"providers" json:"providers"`
+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,
})
}
+106 -13
View File
@@ -56,34 +56,83 @@ type CustomAgent struct {
// CustomAgentConfig represents the configuration of a custom agent
type CustomAgentConfig struct {
// ===== Basic Settings =====
// Agent mode: "normal" for RAG mode, "agent" for ReAct agent mode
AgentMode string `yaml:"agent_mode" json:"agent_mode"`
// System prompt for the agent
// System prompt for the agent (for normal mode, or agent mode when web search is disabled)
SystemPrompt string `yaml:"system_prompt" json:"system_prompt"`
// System prompt for agent mode when web search is enabled
SystemPromptWebEnabled string `yaml:"system_prompt_web_enabled" json:"system_prompt_web_enabled"`
// Context template for normal mode (how to format retrieved chunks)
ContextTemplate string `yaml:"context_template" json:"context_template"`
// ===== Model Settings =====
// Model ID to use for conversations
ModelID string `yaml:"model_id" json:"model_id"`
// ReRank model ID for retrieval
RerankModelID string `yaml:"rerank_model_id" json:"rerank_model_id"`
// Temperature for LLM (0-1)
Temperature float64 `yaml:"temperature" json:"temperature"`
// Maximum completion tokens (only for normal mode)
MaxCompletionTokens int `yaml:"max_completion_tokens" json:"max_completion_tokens"`
// ===== Agent Mode Settings =====
// Maximum iterations for ReAct loop (only for agent type)
MaxIterations int `yaml:"max_iterations" json:"max_iterations"`
// Allowed tools (only for agent type)
AllowedTools []string `yaml:"allowed_tools" json:"allowed_tools"`
// Associated knowledge base IDs
// Whether reflection is enabled (only for agent type)
ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"`
// ===== Knowledge Base Settings =====
// Knowledge base selection mode: "all" = all KBs, "selected" = specific KBs, "none" = no KB
KBSelectionMode string `yaml:"kb_selection_mode" json:"kb_selection_mode"`
// Associated knowledge base IDs (only used when KBSelectionMode is "selected")
KnowledgeBases []string `yaml:"knowledge_bases" json:"knowledge_bases"`
// Whether to allow user to select knowledge bases when no KnowledgeBases are configured
// If true (default), user can freely select any knowledge base
// If false, knowledge base selection is disabled for this agent
// Whether to allow user to select knowledge bases during conversation
// If true, user can select from available KBs (all or selected based on KBSelectionMode)
// If false, the configured KBs are used automatically without user selection
AllowUserKBSelection *bool `yaml:"allow_user_kb_selection" json:"allow_user_kb_selection"`
// ===== Web Search Settings =====
// Whether web search is enabled
WebSearchEnabled bool `yaml:"web_search_enabled" json:"web_search_enabled"`
// Maximum web search results
WebSearchMaxResults int `yaml:"web_search_max_results" json:"web_search_max_results"`
// Whether reflection is enabled (only for agent type)
ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"`
// Welcome message displayed when agent is selected
// ===== Multi-turn Conversation Settings =====
// Whether multi-turn conversation is enabled
MultiTurnEnabled bool `yaml:"multi_turn_enabled" json:"multi_turn_enabled"`
// Number of history turns to keep in context
HistoryTurns int `yaml:"history_turns" json:"history_turns"`
// ===== Retrieval Strategy Settings (for both modes) =====
// Embedding/Vector retrieval top K
EmbeddingTopK int `yaml:"embedding_top_k" json:"embedding_top_k"`
// Keyword retrieval threshold
KeywordThreshold float64 `yaml:"keyword_threshold" json:"keyword_threshold"`
// Vector retrieval threshold
VectorThreshold float64 `yaml:"vector_threshold" json:"vector_threshold"`
// Rerank top K
RerankTopK int `yaml:"rerank_top_k" json:"rerank_top_k"`
// Rerank threshold
RerankThreshold float64 `yaml:"rerank_threshold" json:"rerank_threshold"`
// ===== Advanced Settings (mainly for normal mode) =====
// Whether to enable query expansion
EnableQueryExpansion bool `yaml:"enable_query_expansion" json:"enable_query_expansion"`
// Whether to enable query rewrite for multi-turn conversations
EnableRewrite bool `yaml:"enable_rewrite" json:"enable_rewrite"`
// Rewrite prompt system message
RewritePromptSystem string `yaml:"rewrite_prompt_system" json:"rewrite_prompt_system"`
// Rewrite prompt user message template
RewritePromptUser string `yaml:"rewrite_prompt_user" json:"rewrite_prompt_user"`
// Fallback strategy: "fixed" for fixed response, "model" for model generation
FallbackStrategy string `yaml:"fallback_strategy" json:"fallback_strategy"`
// Fixed fallback response (when FallbackStrategy is "fixed")
FallbackResponse string `yaml:"fallback_response" json:"fallback_response"`
// Fallback prompt (when FallbackStrategy is "model")
FallbackPrompt string `yaml:"fallback_prompt" json:"fallback_prompt"`
}
// Value implements driver.Valuer interface for CustomAgentConfig
@@ -128,6 +177,29 @@ func (a *CustomAgent) EnsureDefaults() {
if a.Config.HistoryTurns == 0 {
a.Config.HistoryTurns = 5
}
// Retrieval strategy defaults
if a.Config.EmbeddingTopK == 0 {
a.Config.EmbeddingTopK = 10
}
if a.Config.KeywordThreshold == 0 {
a.Config.KeywordThreshold = 0.3
}
if a.Config.VectorThreshold == 0 {
a.Config.VectorThreshold = 0.5
}
if a.Config.RerankTopK == 0 {
a.Config.RerankTopK = 5
}
if a.Config.RerankThreshold == 0 {
a.Config.RerankThreshold = 0.5
}
// Advanced settings defaults
if a.Config.FallbackStrategy == "" {
a.Config.FallbackStrategy = "model"
}
if a.Config.MaxCompletionTokens == 0 {
a.Config.MaxCompletionTokens = 2048
}
}
// IsAgentMode returns true if this agent uses ReAct agent mode
@@ -146,10 +218,23 @@ func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {
Type: CustomAgentTypeNormal,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: "normal",
SystemPrompt: "",
Temperature: 0.7,
WebSearchEnabled: false,
AgentMode: "normal",
SystemPrompt: "",
Temperature: 0.7,
MaxCompletionTokens: 2048,
WebSearchEnabled: false,
MultiTurnEnabled: true,
HistoryTurns: 5,
// Retrieval strategy
EmbeddingTopK: 10,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 5,
RerankThreshold: 0.5,
// Advanced settings
EnableQueryExpansion: true,
EnableRewrite: true,
FallbackStrategy: "model",
},
}
}
@@ -169,10 +254,18 @@ func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
SystemPrompt: "",
Temperature: 0.7,
MaxIterations: 10,
AllowedTools: []string{"knowledge_search", "web_search"},
AllowedTools: []string{"thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"},
WebSearchEnabled: true,
WebSearchMaxResults: 5,
ReflectionEnabled: false,
MultiTurnEnabled: true,
HistoryTurns: 5,
// Retrieval strategy
EmbeddingTopK: 10,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 5,
RerankThreshold: 0.5,
},
}
}
+3 -2
View File
@@ -65,14 +65,15 @@ type CustomAgentRepository interface {
// - Possible errors such as database connection failure, unique constraint conflicts, etc.
CreateAgent(ctx context.Context, agent *types.CustomAgent) error
// GetAgentByID queries an agent by ID
// GetAgentByID queries an agent by ID and tenant
// Parameters:
// - ctx: Context information
// - id: Agent ID
// - tenantID: Tenant ID for isolation
// Returns:
// - Agent object, if found
// - Possible errors such as record not existing, database errors, etc.
GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error)
GetAgentByID(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error)
// ListAgentsByTenantID lists all agents for a specific tenant
// Parameters:
+16 -16
View File
@@ -80,22 +80,22 @@ type Session struct {
// Tenant ID
TenantID uint64 `json:"tenant_id" gorm:"index"`
// Strategy configuration
KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID
MaxRounds int `json:"max_rounds"` // 多轮保持轮数
EnableRewrite bool `json:"enable_rewrite"` // 多轮改写开关
FallbackStrategy FallbackStrategy `json:"fallback_strategy"` // 兜底策略
FallbackResponse string `json:"fallback_response"` // 固定回复内容
EmbeddingTopK int `json:"embedding_top_k"` // 向量召回TopK
KeywordThreshold float64 `json:"keyword_threshold"` // 关键词召回阈值
VectorThreshold float64 `json:"vector_threshold"` // 向量召回阈值
RerankModelID string `json:"rerank_model_id"` // 排序模型ID
RerankTopK int `json:"rerank_top_k"` // 排序TopK
RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值
SummaryModelID string `json:"summary_model_id"` // 总结模型ID
SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数
AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:jsonb"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases)
ContextConfig *ContextConfig `json:"context_config" gorm:"type:jsonb"` // 上下文管理配置(可选)
// // Strategy configuration
// KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID
// MaxRounds int `json:"max_rounds"` // 多轮保持轮数
// EnableRewrite bool `json:"enable_rewrite"` // 多轮改写开关
// FallbackStrategy FallbackStrategy `json:"fallback_strategy"` // 兜底策略
// FallbackResponse string `json:"fallback_response"` // 固定回复内容
// EmbeddingTopK int `json:"embedding_top_k"` // 向量召回TopK
// KeywordThreshold float64 `json:"keyword_threshold"` // 关键词召回阈值
// VectorThreshold float64 `json:"vector_threshold"` // 向量召回阈值
// RerankModelID string `json:"rerank_model_id"` // 排序模型ID
// RerankTopK int `json:"rerank_top_k"` // 排序TopK
// RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值
// SummaryModelID string `json:"summary_model_id"` // 总结模型ID
// SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数
// AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:jsonb"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases)
// ContextConfig *ContextConfig `json:"context_config" gorm:"type:jsonb"` // 上下文管理配置(可选)
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
+1 -3
View File
@@ -126,9 +126,7 @@ func (c *RetrieverEngines) Scan(value interface{}) error {
// ConversationConfig represents the conversation configuration for normal mode
type ConversationConfig struct {
// Prompt is the system prompt for normal mode
UseCustomSystemPrompt bool `json:"use_custom_system_prompt"`
Prompt string `json:"prompt"`
UseCustomContextTemplate bool `json:"use_custom_context_template"`
Prompt string `json:"prompt"`
// ContextTemplate is the prompt template for summarizing retrieval results
ContextTemplate string `json:"context_template"`
// Temperature controls the randomness of the model output