feat: 新增智能体功能模块,支持自定义智能体创建、配置和选择

This commit is contained in:
wizardchen
2025-12-24 10:34:41 +08:00
parent 236b190b26
commit d0c5c4f6b0
36 changed files with 5195 additions and 672 deletions
@@ -0,0 +1,62 @@
package repository
import (
"context"
"errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
// ErrCustomAgentNotFound is returned when a custom agent is not found
var ErrCustomAgentNotFound = errors.New("custom agent not found")
// customAgentRepository implements the CustomAgentRepository interface
type customAgentRepository struct {
db *gorm.DB
}
// NewCustomAgentRepository creates a new custom agent repository
func NewCustomAgentRepository(db *gorm.DB) interfaces.CustomAgentRepository {
return &customAgentRepository{db: db}
}
// CreateAgent creates a new custom agent
func (r *customAgentRepository) CreateAgent(ctx context.Context, agent *types.CustomAgent) error {
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) {
var agent types.CustomAgent
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&agent).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrCustomAgentNotFound
}
return nil, err
}
return &agent, nil
}
// ListAgentsByTenantID lists all agents for a specific tenant
func (r *customAgentRepository) ListAgentsByTenantID(ctx context.Context, tenantID uint64) ([]*types.CustomAgent, error) {
var agents []*types.CustomAgent
if err := r.db.WithContext(ctx).
Where("tenant_id = ?", tenantID).
Order("created_at DESC").
Find(&agents).Error; err != nil {
return nil, err
}
return agents, nil
}
// UpdateAgent updates an agent
func (r *customAgentRepository) UpdateAgent(ctx context.Context, agent *types.CustomAgent) error {
return r.db.WithContext(ctx).Save(agent).Error
}
// DeleteAgent deletes an agent (soft delete)
func (r *customAgentRepository) DeleteAgent(ctx context.Context, id string) error {
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.CustomAgent{}).Error
}
+11 -3
View File
@@ -179,8 +179,16 @@ func (s *agentService) registerTools(
sessionID string,
sessionService interfaces.SessionService,
) error {
// If no specific tools allowed, register default tools
allowedTools := tools.DefaultAllowedTools()
// Use config's allowed tools if specified, otherwise use defaults
var allowedTools []string
if len(config.AllowedTools) > 0 {
allowedTools = make([]string, len(config.AllowedTools))
copy(allowedTools, config.AllowedTools)
logger.Infof(ctx, "Using custom allowed tools from config: %v", allowedTools)
} else {
allowedTools = tools.DefaultAllowedTools()
logger.Infof(ctx, "Using default allowed tools: %v", allowedTools)
}
// Filter out knowledge base tools if no knowledge bases or knowledge IDs are configured
hasKnowledge := len(config.KnowledgeBases) > 0 || len(config.KnowledgeIDs) > 0
@@ -206,7 +214,7 @@ func (s *agentService) registerTools(
}
}
allowedTools = filteredTools
logger.Infof(ctx, "Pure Agent Mode: Knowledge base tools disabled due to empty configuration")
logger.Infof(ctx, "Pure Agent Mode: Knowledge base tools filtered out, remaining: %v", allowedTools)
}
// If web search is enabled, add web_search to allowedTools
@@ -0,0 +1,267 @@
package service
import (
"context"
"errors"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
// Custom agent related errors
var (
ErrAgentNotFound = errors.New("agent not found")
ErrCannotModifyBuiltin = errors.New("cannot modify built-in agent")
ErrCannotDeleteBuiltin = errors.New("cannot delete built-in agent")
ErrAgentNameRequired = errors.New("agent name is required")
)
// customAgentService implements the CustomAgentService interface
type customAgentService struct {
repo interfaces.CustomAgentRepository
}
// NewCustomAgentService creates a new custom agent service
func NewCustomAgentService(repo interfaces.CustomAgentRepository) interfaces.CustomAgentService {
return &customAgentService{
repo: repo,
}
}
// CreateAgent creates a new custom agent
func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) {
// Validate required fields
if strings.TrimSpace(agent.Name) == "" {
return nil, ErrAgentNameRequired
}
// Generate UUID and set creation timestamps
if agent.ID == "" {
agent.ID = uuid.New().String()
}
// Get tenant ID from context
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return nil, ErrInvalidTenantID
}
agent.TenantID = tenantID
// Set timestamps
agent.CreatedAt = time.Now()
agent.UpdatedAt = time.Now()
// Ensure custom type for user-created agents
if agent.Type == "" {
agent.Type = types.CustomAgentTypeCustom
}
// Cannot create built-in agents
agent.IsBuiltin = false
// Set defaults
agent.EnsureDefaults()
logger.Infof(ctx, "Creating custom agent, ID: %s, tenant ID: %d, name: %s, type: %s",
agent.ID, agent.TenantID, agent.Name, agent.Type)
if err := s.repo.CreateAgent(ctx, agent); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": agent.ID,
"tenant_id": agent.TenantID,
})
return nil, err
}
logger.Infof(ctx, "Custom agent created successfully, ID: %s, name: %s", agent.ID, agent.Name)
return agent, nil
}
// GetAgentByID retrieves an agent by its ID (including built-in agents)
func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) {
if id == "" {
logger.Error(ctx, "Agent ID is empty")
return nil, errors.New("agent ID cannot be empty")
}
// Get tenant ID from context
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return nil, ErrInvalidTenantID
}
// Check if it's a built-in agent
if id == types.BuiltinAgentNormalID {
return types.GetBuiltinNormalAgent(tenantID), nil
}
if id == types.BuiltinAgentAgentID {
return types.GetBuiltinAgentAgent(tenantID), nil
}
// Query from database
agent, err := s.repo.GetAgentByID(ctx, id)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return nil, ErrAgentNotFound
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": id,
})
return nil, err
}
// Verify tenant ownership
if agent.TenantID != tenantID {
return nil, ErrAgentNotFound
}
return agent, nil
}
// ListAgents lists all agents for the current tenant (including built-in agents)
func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAgent, error) {
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return nil, ErrInvalidTenantID
}
// Get built-in agents first
builtinAgents := types.GetBuiltinAgents(tenantID)
// Get custom agents from database
customAgents, err := s.repo.ListAgentsByTenantID(ctx, tenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"tenant_id": tenantID,
})
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...)
return result, nil
}
// UpdateAgent updates an agent's information
func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) {
if agent.ID == "" {
logger.Error(ctx, "Agent ID is empty")
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
}
// Get existing agent
existingAgent, err := s.repo.GetAgentByID(ctx, agent.ID)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return nil, ErrAgentNotFound
}
return nil, err
}
// Verify tenant ownership
if existingAgent.TenantID != tenantID {
return nil, ErrAgentNotFound
}
// Cannot modify built-in status
if existingAgent.IsBuiltin {
return nil, ErrCannotModifyBuiltin
}
// Validate name
if strings.TrimSpace(agent.Name) == "" {
return nil, ErrAgentNameRequired
}
// Update fields
existingAgent.Name = agent.Name
existingAgent.Description = agent.Description
existingAgent.Avatar = agent.Avatar
existingAgent.Type = agent.Type
existingAgent.Config = agent.Config
existingAgent.UpdatedAt = time.Now()
// Ensure defaults
existingAgent.EnsureDefaults()
logger.Infof(ctx, "Updating custom agent, ID: %s, name: %s", agent.ID, agent.Name)
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, "Custom agent updated successfully, ID: %s", agent.ID)
return existingAgent, nil
}
// DeleteAgent deletes an agent
func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {
if id == "" {
logger.Error(ctx, "Agent ID is empty")
return errors.New("agent ID cannot be empty")
}
// Cannot delete built-in agents
if id == types.BuiltinAgentNormalID || id == types.BuiltinAgentAgentID {
return ErrCannotDeleteBuiltin
}
// Get tenant ID from context
tenantID, ok := ctx.Value(types.TenantIDContextKey).(uint64)
if !ok {
return ErrInvalidTenantID
}
// Get existing agent to verify ownership
existingAgent, err := s.repo.GetAgentByID(ctx, id)
if err != nil {
if errors.Is(err, repository.ErrCustomAgentNotFound) {
return ErrAgentNotFound
}
return err
}
// Verify tenant ownership
if existingAgent.TenantID != tenantID {
return ErrAgentNotFound
}
// Cannot delete built-in agents
if existingAgent.IsBuiltin {
return ErrCannotDeleteBuiltin
}
logger.Infof(ctx, "Deleting custom agent, ID: %s", id)
if err := s.repo.DeleteAgent(ctx, id); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"agent_id": id,
})
return err
}
logger.Infof(ctx, "Custom agent deleted successfully, ID: %s", id)
return nil
}
@@ -166,3 +166,42 @@ func (cm *contextManager) GetContextStats(ctx context.Context, sessionID string)
return stats, nil
}
// SetSystemPrompt sets or updates the system prompt for a session
// If a system message exists, it will be replaced; otherwise, a new one will be added at the beginning
func (cm *contextManager) SetSystemPrompt(ctx context.Context, sessionID string, systemPrompt string) error {
logger.Infof(ctx, "[ContextManager][Session-%s] Setting system prompt, length=%d", sessionID, len(systemPrompt))
// Load existing messages from storage
messages, err := cm.storage.Load(ctx, sessionID)
if err != nil {
logger.Errorf(ctx, "[ContextManager][Session-%s] Failed to load context: %v", sessionID, err)
return fmt.Errorf("failed to load context: %w", err)
}
// Create new system message
systemMessage := chat.Message{
Role: "system",
Content: systemPrompt,
}
// Check if first message is a system message
if len(messages) > 0 && messages[0].Role == "system" {
// Replace existing system message
logger.Debugf(ctx, "[ContextManager][Session-%s] Replacing existing system prompt", sessionID)
messages[0] = systemMessage
} else {
// Insert system message at the beginning
logger.Debugf(ctx, "[ContextManager][Session-%s] Inserting new system prompt at beginning", sessionID)
messages = append([]chat.Message{systemMessage}, messages...)
}
// Save updated messages to storage
if err := cm.storage.Save(ctx, sessionID, messages); err != nil {
logger.Errorf(ctx, "[ContextManager][Session-%s] Failed to save context: %v", sessionID, err)
return fmt.Errorf("failed to save context: %w", err)
}
logger.Infof(ctx, "[ContextManager][Session-%s] System prompt set successfully", sessionID)
return nil
}
+140 -20
View File
@@ -392,6 +392,7 @@ func (s *sessionService) GenerateTitleAsync(
// KnowledgeQA performs knowledge base question answering with LLM summarization
// Events are emitted through eventBus (references, answer chunks, completion)
// customAgent is optional - if provided, uses custom agent configuration for multiTurnEnabled and historyTurns
func (s *sessionService) KnowledgeQA(
ctx context.Context,
session *types.Session,
@@ -402,6 +403,7 @@ func (s *sessionService) KnowledgeQA(
summaryModelID string,
webSearchEnabled bool,
eventBus *event.EventBus,
customAgent *types.CustomAgent,
) error {
logger.Infof(
ctx,
@@ -421,6 +423,22 @@ func (s *sessionService) KnowledgeQA(
}
}
// 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
existingKBs := make(map[string]bool)
for _, kbID := range knowledgeBaseIDs {
existingKBs[kbID] = true
}
// Add agent's knowledge bases that are not already in the list
for _, kbID := range customAgent.Config.KnowledgeBases {
if !existingKBs[kbID] {
knowledgeBaseIDs = append(knowledgeBaseIDs, kbID)
logger.Infof(ctx, "Adding custom agent's knowledge base: %s", kbID)
}
}
}
logger.Infof(ctx, "Using knowledge bases: %v", knowledgeBaseIDs)
// Determine chat model ID: prioritize request's summaryModelID, then Remote models
@@ -514,6 +532,32 @@ func (s *sessionService) KnowledgeQA(
logger.Infof(ctx, "Fallback strategy not set, using default: %v", fallbackStrategy)
}
// Apply custom agent configuration if provided
multiTurnEnabled := true // Default: enable multi-turn
if customAgent != nil {
// Override system prompt with customAgent's SystemPrompt
if customAgent.Config.SystemPrompt != "" {
summaryConfig.Prompt = customAgent.Config.SystemPrompt
logger.Infof(ctx, "Using custom agent's system_prompt")
}
// Override temperature with customAgent's 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
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 {
maxRounds = 0 // Disable history
logger.Infof(ctx, "Multi-turn disabled by custom agent, clearing history")
}
}
// Build unified search targets (computed once, used throughout pipeline)
searchTargets, err := s.buildSearchTargets(ctx, session.TenantID, knowledgeBaseIDs, knowledgeIDs)
if err != nil {
@@ -962,12 +1006,14 @@ func (s *sessionService) SearchKnowledge(ctx context.Context,
}
// AgentQA performs agent-based question answering with conversation history and streaming support
// customAgent is optional - if provided, uses custom agent configuration instead of tenant defaults
func (s *sessionService) AgentQA(
ctx context.Context,
session *types.Session,
query string,
assistantMessageID string,
eventBus *event.EventBus,
customAgent *types.CustomAgent,
) error {
sessionID := session.ID
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
@@ -1004,29 +1050,82 @@ func (s *sessionService) AgentQA(
}
}
// Create runtime AgentConfig by merging session and tenant configs
// Tenant config provides the runtime parameters (MaxIterations, Temperature, Tools, Models)
// Create runtime AgentConfig
// Priority: CustomAgent config > Tenant config > Defaults
// Session config provides KnowledgeBases and KnowledgeIDs
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
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)
}
}
agentConfig.UseCustomSystemPrompt = tenantInfo.AgentConfig.UseCustomSystemPrompt
if agentConfig.UseCustomSystemPrompt {
agentConfig.SystemPromptWebEnabled = tenantInfo.AgentConfig.ResolveSystemPrompt(true)
agentConfig.SystemPromptWebDisabled = tenantInfo.AgentConfig.ResolveSystemPrompt(false)
}
// Set web search max results from tenant config (default: 5)
agentConfig.WebSearchMaxResults = 5
if tenantInfo.WebSearchConfig != nil && tenantInfo.WebSearchConfig.MaxResults > 0 {
agentConfig.WebSearchMaxResults = tenantInfo.WebSearchConfig.MaxResults
// Set web search max results from tenant config if not set (default: 5)
if agentConfig.WebSearchMaxResults == 0 {
agentConfig.WebSearchMaxResults = 5
if tenantInfo.WebSearchConfig != nil && tenantInfo.WebSearchConfig.MaxResults > 0 {
agentConfig.WebSearchMaxResults = tenantInfo.WebSearchConfig.MaxResults
}
}
logger.Infof(ctx, "Merged agent config from tenant %d and session %s", tenantInfo.ID, sessionID)
@@ -1099,6 +1198,18 @@ func (s *sessionService) AgentQA(
// Get or create contextManager for this session
contextManager := s.getContextManagerForSession(ctx, session, summaryModel)
// Set system prompt for the current agent in context manager
// This ensures the context uses the correct system prompt when switching agents
systemPrompt := agentConfig.ResolveSystemPrompt(agentConfig.WebSearchEnabled)
if systemPrompt != "" {
if err := contextManager.SetSystemPrompt(ctx, sessionID, systemPrompt); err != nil {
logger.Warnf(ctx, "Failed to set system prompt in context manager: %v", err)
} else {
logger.Infof(ctx, "System prompt updated in context manager for agent")
}
}
// Get LLM context from context manager
llmContext, err := s.getContextForSession(ctx, contextManager, sessionID)
if err != nil {
@@ -1107,6 +1218,15 @@ func (s *sessionService) AgentQA(
}
logger.Infof(ctx, "Loaded %d messages from LLM context manager", len(llmContext))
// Apply multi-turn configuration for Agent mode
// Note: In Agent mode, context is managed by contextManager with compression strategies,
// so we don't apply HistoryTurns limit here. HistoryTurns is used in normal (KnowledgeQA) mode.
if !agentConfig.MultiTurnEnabled {
// Multi-turn disabled, clear history
logger.Infof(ctx, "Multi-turn disabled for this agent, clearing history context")
llmContext = []chat.Message{}
}
// Create agent engine with EventBus and ContextManager
logger.Info(ctx, "Creating agent engine")
engine, err := s.agentService.CreateAgentEngine(