feat: 重构提示词模板系统,新增多场景模板配置支持;优化智能体知识库选择模式,支持全部/指定/禁用三种模式
This commit is contained in:
@@ -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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user