feat: 新增智能体功能模块,支持自定义智能体创建、配置和选择
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -97,6 +97,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(repository.NewAuthTokenRepository))
|
||||
must(container.Provide(neo4jRepo.NewNeo4jRepository))
|
||||
must(container.Provide(repository.NewMCPServiceRepository))
|
||||
must(container.Provide(repository.NewCustomAgentRepository))
|
||||
|
||||
// MCP manager for managing MCP client connections
|
||||
must(container.Provide(mcp.NewMCPManager))
|
||||
@@ -115,6 +116,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(service.NewChunkExtractService))
|
||||
must(container.Provide(service.NewMessageService))
|
||||
must(container.Provide(service.NewMCPServiceService))
|
||||
must(container.Provide(service.NewCustomAgentService))
|
||||
|
||||
// Web search service (needed by AgentService)
|
||||
must(container.Provide(service.NewWebSearchService))
|
||||
@@ -163,6 +165,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(handler.NewSystemHandler))
|
||||
must(container.Provide(handler.NewMCPServiceHandler))
|
||||
must(container.Provide(handler.NewWebSearchHandler))
|
||||
must(container.Provide(handler.NewCustomAgentHandler))
|
||||
|
||||
// Router configuration
|
||||
must(container.Provide(router.NewRouter))
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CustomAgentHandler defines the HTTP handler for custom agent operations
|
||||
type CustomAgentHandler struct {
|
||||
service interfaces.CustomAgentService
|
||||
}
|
||||
|
||||
// NewCustomAgentHandler creates a new custom agent handler instance
|
||||
func NewCustomAgentHandler(service interfaces.CustomAgentService) *CustomAgentHandler {
|
||||
return &CustomAgentHandler{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateAgentRequest defines the request body for creating an agent
|
||||
type CreateAgentRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Description string `json:"description"`
|
||||
Avatar string `json:"avatar"`
|
||||
Type types.CustomAgentType `json:"type"`
|
||||
Config types.CustomAgentConfig `json:"config"`
|
||||
}
|
||||
|
||||
// UpdateAgentRequest defines the request body for updating an agent
|
||||
type UpdateAgentRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Description string `json:"description"`
|
||||
Avatar string `json:"avatar"`
|
||||
Type types.CustomAgentType `json:"type"`
|
||||
Config types.CustomAgentConfig `json:"config"`
|
||||
}
|
||||
|
||||
// CreateAgent godoc
|
||||
// @Summary 创建智能体
|
||||
// @Description 创建新的自定义智能体
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body CreateAgentRequest true "智能体信息"
|
||||
// @Success 201 {object} map[string]interface{} "创建的智能体"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents [post]
|
||||
func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start creating custom agent")
|
||||
|
||||
// Parse request body
|
||||
var req CreateAgentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Build agent object
|
||||
agent := &types.CustomAgent{
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
Avatar: req.Avatar,
|
||||
Type: req.Type,
|
||||
Config: req.Config,
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Creating custom agent, name: %s, type: %s",
|
||||
secutils.SanitizeForLog(req.Name), req.Type)
|
||||
|
||||
// Create agent using the service
|
||||
createdAgent, err := h.service.CreateAgent(ctx, agent)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
if err == service.ErrAgentNameRequired {
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent created successfully, ID: %s, name: %s",
|
||||
secutils.SanitizeForLog(createdAgent.ID), secutils.SanitizeForLog(createdAgent.Name))
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"success": true,
|
||||
"data": createdAgent,
|
||||
})
|
||||
}
|
||||
|
||||
// GetAgent godoc
|
||||
// @Summary 获取智能体详情
|
||||
// @Description 根据ID获取智能体详情
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "智能体ID"
|
||||
// @Success 200 {object} map[string]interface{} "智能体详情"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 404 {object} errors.AppError "智能体不存在"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents/{id} [get]
|
||||
func (h *CustomAgentHandler) GetAgent(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get agent ID from URL parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Agent ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
agent, err := h.service.GetAgentByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
})
|
||||
if err == service.ErrAgentNotFound {
|
||||
c.Error(errors.NewNotFoundError("Agent not found"))
|
||||
return
|
||||
}
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": agent,
|
||||
})
|
||||
}
|
||||
|
||||
// ListAgents godoc
|
||||
// @Summary 获取智能体列表
|
||||
// @Description 获取当前租户的所有智能体(包括内置智能体)
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} map[string]interface{} "智能体列表"
|
||||
// @Failure 500 {object} errors.AppError "服务器错误"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents [get]
|
||||
func (h *CustomAgentHandler) ListAgents(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
// Get all agents for this tenant
|
||||
agents, err := h.service.ListAgents(ctx)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": agents,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateAgent godoc
|
||||
// @Summary 更新智能体
|
||||
// @Description 更新智能体的名称、描述和配置
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "智能体ID"
|
||||
// @Param request body UpdateAgentRequest true "更新请求"
|
||||
// @Success 200 {object} map[string]interface{} "更新后的智能体"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 403 {object} errors.AppError "无法修改内置智能体"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents/{id} [put]
|
||||
func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start updating custom agent")
|
||||
|
||||
// Get agent ID from URL parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Agent ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var req UpdateAgentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request parameters", err)
|
||||
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Build agent object
|
||||
agent := &types.CustomAgent{
|
||||
ID: id,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
Avatar: req.Avatar,
|
||||
Type: req.Type,
|
||||
Config: req.Config,
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Updating custom agent, ID: %s, name: %s",
|
||||
secutils.SanitizeForLog(id), secutils.SanitizeForLog(req.Name))
|
||||
|
||||
// Update the agent
|
||||
updatedAgent, err := h.service.UpdateAgent(ctx, agent)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
})
|
||||
switch err {
|
||||
case service.ErrAgentNotFound:
|
||||
c.Error(errors.NewNotFoundError("Agent not found"))
|
||||
case service.ErrCannotModifyBuiltin:
|
||||
c.Error(errors.NewForbiddenError("Cannot modify built-in agent"))
|
||||
case service.ErrAgentNameRequired:
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
default:
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent updated successfully, ID: %s", secutils.SanitizeForLog(id))
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": updatedAgent,
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteAgent godoc
|
||||
// @Summary 删除智能体
|
||||
// @Description 删除指定的智能体
|
||||
// @Tags 智能体
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "智能体ID"
|
||||
// @Success 200 {object} map[string]interface{} "删除成功"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 403 {object} errors.AppError "无法删除内置智能体"
|
||||
// @Failure 404 {object} errors.AppError "智能体不存在"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /agents/{id} [delete]
|
||||
func (h *CustomAgentHandler) DeleteAgent(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
logger.Info(ctx, "Start deleting custom agent")
|
||||
|
||||
// Get agent ID from URL parameter
|
||||
id := secutils.SanitizeForLog(c.Param("id"))
|
||||
if id == "" {
|
||||
logger.Error(ctx, "Agent ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Agent ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Deleting custom agent, ID: %s", secutils.SanitizeForLog(id))
|
||||
|
||||
// Delete the agent
|
||||
err := h.service.DeleteAgent(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
})
|
||||
switch err {
|
||||
case service.ErrAgentNotFound:
|
||||
c.Error(errors.NewNotFoundError("Agent not found"))
|
||||
case service.ErrCannotDeleteBuiltin:
|
||||
c.Error(errors.NewForbiddenError("Cannot delete built-in agent"))
|
||||
default:
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Custom agent deleted successfully, ID: %s", secutils.SanitizeForLog(id))
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "Agent deleted successfully",
|
||||
})
|
||||
}
|
||||
@@ -20,6 +20,7 @@ type Handler struct {
|
||||
streamManager interfaces.StreamManager // Manager for handling streaming responses
|
||||
config *config.Config // Application configuration
|
||||
knowledgebaseService interfaces.KnowledgeBaseService // Service for managing knowledge bases
|
||||
customAgentService interfaces.CustomAgentService // Service for managing custom agents
|
||||
}
|
||||
|
||||
// NewHandler creates a new instance of Handler with all necessary dependencies
|
||||
@@ -29,6 +30,7 @@ func NewHandler(
|
||||
streamManager interfaces.StreamManager,
|
||||
config *config.Config,
|
||||
knowledgebaseService interfaces.KnowledgeBaseService,
|
||||
customAgentService interfaces.CustomAgentService,
|
||||
) *Handler {
|
||||
return &Handler{
|
||||
sessionService: sessionService,
|
||||
@@ -36,6 +38,7 @@ func NewHandler(
|
||||
streamManager: streamManager,
|
||||
config: config,
|
||||
knowledgebaseService: knowledgebaseService,
|
||||
customAgentService: customAgentService,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+406
-455
@@ -16,6 +16,256 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// qaRequestContext holds all the common data needed for QA requests
|
||||
type qaRequestContext struct {
|
||||
ctx context.Context
|
||||
c *gin.Context
|
||||
sessionID string
|
||||
requestID string
|
||||
query string
|
||||
session *types.Session
|
||||
customAgent *types.CustomAgent
|
||||
assistantMessage *types.Message
|
||||
knowledgeBaseIDs []string
|
||||
knowledgeIDs []string
|
||||
summaryModelID string
|
||||
webSearchEnabled bool
|
||||
mentionedItems types.MentionedItems
|
||||
}
|
||||
|
||||
// parseQARequest parses and validates a QA request, returns the request context
|
||||
func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestContext, *CreateKnowledgeQARequest, error) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
logger.Infof(ctx, "[%s] Start processing request", logPrefix)
|
||||
|
||||
// Get session ID from URL parameter
|
||||
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
|
||||
if sessionID == "" {
|
||||
logger.Error(ctx, "Session ID is empty")
|
||||
return nil, nil, errors.NewBadRequestError(errors.ErrInvalidSessionID.Error())
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var request CreateKnowledgeQARequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request data", err)
|
||||
return nil, nil, errors.NewBadRequestError(err.Error())
|
||||
}
|
||||
|
||||
// Validate query content
|
||||
if request.Query == "" {
|
||||
logger.Error(ctx, "Query content is empty")
|
||||
return nil, nil, errors.NewBadRequestError("Query content cannot be empty")
|
||||
}
|
||||
|
||||
// Log request details
|
||||
if requestJSON, err := json.Marshal(request); err == nil {
|
||||
logger.Infof(ctx, "[%s] Request: session_id=%s, request=%s",
|
||||
logPrefix, sessionID, secutils.SanitizeForLog(string(requestJSON)))
|
||||
}
|
||||
|
||||
// Get session
|
||||
session, err := h.sessionService.GetSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
|
||||
return nil, nil, errors.NewNotFoundError("Session not found")
|
||||
}
|
||||
|
||||
// Get custom agent if agent_id is provided
|
||||
var customAgent *types.CustomAgent
|
||||
if request.AgentID != "" {
|
||||
logger.Infof(ctx, "Fetching custom agent, agent ID: %s", secutils.SanitizeForLog(request.AgentID))
|
||||
agent, err := h.customAgentService.GetAgentByID(ctx, request.AgentID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to get custom agent, agent ID: %s, error: %v, using default config",
|
||||
secutils.SanitizeForLog(request.AgentID), err)
|
||||
} else {
|
||||
customAgent = agent
|
||||
logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, Type=%s, AgentMode=%s",
|
||||
customAgent.ID, customAgent.Name, customAgent.Type, customAgent.Config.AgentMode)
|
||||
}
|
||||
}
|
||||
|
||||
// Build request context
|
||||
reqCtx := &qaRequestContext{
|
||||
ctx: ctx,
|
||||
c: c,
|
||||
sessionID: sessionID,
|
||||
requestID: secutils.SanitizeForLog(c.GetString(types.RequestIDContextKey.String())),
|
||||
query: secutils.SanitizeForLog(request.Query),
|
||||
session: session,
|
||||
customAgent: customAgent,
|
||||
assistantMessage: &types.Message{
|
||||
SessionID: sessionID,
|
||||
Role: "assistant",
|
||||
RequestID: c.GetString(types.RequestIDContextKey.String()),
|
||||
IsCompleted: false,
|
||||
},
|
||||
knowledgeBaseIDs: secutils.SanitizeForLogArray(request.KnowledgeBaseIDs),
|
||||
knowledgeIDs: secutils.SanitizeForLogArray(request.KnowledgeIds),
|
||||
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
|
||||
webSearchEnabled: request.WebSearchEnabled,
|
||||
mentionedItems: convertMentionedItems(request.MentionedItems),
|
||||
}
|
||||
|
||||
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
|
||||
asyncCtx context.Context
|
||||
cancel context.CancelFunc
|
||||
assistantMessage *types.Message
|
||||
}
|
||||
|
||||
// setupSSEStream sets up the SSE streaming context
|
||||
func (h *Handler) setupSSEStream(reqCtx *qaRequestContext) *sseStreamContext {
|
||||
// Set SSE headers
|
||||
setSSEHeaders(reqCtx.c)
|
||||
|
||||
// Write initial agent_query event
|
||||
h.writeAgentQueryEvent(reqCtx.ctx, reqCtx.sessionID, reqCtx.assistantMessage.ID)
|
||||
|
||||
// Create EventBus and cancellable context
|
||||
eventBus := event.NewEventBus()
|
||||
asyncCtx, cancel := context.WithCancel(logger.CloneContext(reqCtx.ctx))
|
||||
|
||||
streamCtx := &sseStreamContext{
|
||||
eventBus: eventBus,
|
||||
asyncCtx: asyncCtx,
|
||||
cancel: cancel,
|
||||
assistantMessage: reqCtx.assistantMessage,
|
||||
}
|
||||
|
||||
// Setup stop event handler
|
||||
h.setupStopEventHandler(eventBus, reqCtx.sessionID, reqCtx.assistantMessage, cancel)
|
||||
|
||||
// Setup stream handler
|
||||
h.setupStreamHandler(asyncCtx, reqCtx.sessionID, reqCtx.assistantMessage.ID,
|
||||
reqCtx.requestID, reqCtx.assistantMessage, eventBus)
|
||||
|
||||
// Generate title if needed
|
||||
if reqCtx.session.Title == "" {
|
||||
logger.Infof(reqCtx.ctx, "Session has no title, starting async title generation, session ID: %s", reqCtx.sessionID)
|
||||
h.sessionService.GenerateTitleAsync(asyncCtx, reqCtx.session, reqCtx.query, eventBus)
|
||||
}
|
||||
|
||||
return streamCtx
|
||||
}
|
||||
|
||||
// SearchKnowledge godoc
|
||||
// @Summary 知识搜索
|
||||
// @Description 在知识库中搜索(不使用LLM总结)
|
||||
@@ -30,7 +280,6 @@ import (
|
||||
// @Router /sessions/search [post]
|
||||
func (h *Handler) SearchKnowledge(c *gin.Context) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
|
||||
logger.Info(ctx, "Start processing knowledge search request")
|
||||
|
||||
// Parse request body
|
||||
@@ -54,14 +303,11 @@ func (h *Handler) SearchKnowledge(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Knowledge search request, knowledge base ID: %s, query: %s",
|
||||
logger.Infof(ctx, "Knowledge search request, knowledge base ID: %s, query: %s",
|
||||
secutils.SanitizeForLog(request.KnowledgeBaseID),
|
||||
secutils.SanitizeForLog(request.Query),
|
||||
)
|
||||
secutils.SanitizeForLog(request.Query))
|
||||
|
||||
// Directly call knowledge retrieval service without LLM summarization
|
||||
// Perform search
|
||||
searchResults, err := h.sessionService.SearchKnowledge(ctx, request.KnowledgeBaseID, request.Query)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
@@ -70,8 +316,6 @@ func (h *Handler) SearchKnowledge(c *gin.Context) {
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Knowledge search completed, found %d results", len(searchResults))
|
||||
|
||||
// Return search results
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": searchResults,
|
||||
@@ -92,73 +336,15 @@ func (h *Handler) SearchKnowledge(c *gin.Context) {
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /sessions/{session_id}/knowledge-qa [post]
|
||||
func (h *Handler) KnowledgeQA(c *gin.Context) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
|
||||
logger.Info(ctx, "Start processing knowledge QA request")
|
||||
|
||||
// Get session ID from URL parameter
|
||||
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
|
||||
if sessionID == "" {
|
||||
logger.Error(ctx, "Session ID is empty")
|
||||
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var request CreateKnowledgeQARequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request data", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Create assistant message
|
||||
assistantMessage := &types.Message{
|
||||
SessionID: sessionID,
|
||||
Role: "assistant",
|
||||
RequestID: c.GetString(types.RequestIDContextKey.String()),
|
||||
IsCompleted: false,
|
||||
}
|
||||
|
||||
// Validate query content
|
||||
if request.Query == "" {
|
||||
logger.Error(ctx, "Query content is empty")
|
||||
c.Error(errors.NewBadRequestError("Query content cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Knowledge QA request, session ID: %s, query: %s",
|
||||
sessionID,
|
||||
secutils.SanitizeForLog(request.Query),
|
||||
)
|
||||
|
||||
// Get session to prepare knowledge base IDs
|
||||
session, err := h.sessionService.GetSession(ctx, sessionID)
|
||||
// Parse and validate request
|
||||
reqCtx, _, err := h.parseQARequest(c, "KnowledgeQA")
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Prepare knowledge base IDs
|
||||
knowledgeBaseIDs := request.KnowledgeBaseIDs
|
||||
// if len(knowledgeBaseIDs) == 0 && session.KnowledgeBaseID != "" {
|
||||
// knowledgeBaseIDs = []string{session.KnowledgeBaseID}
|
||||
// logger.Infof(
|
||||
// ctx,
|
||||
// "No knowledge base IDs in request, using session default: %s",
|
||||
// secutils.SanitizeForLog(session.KnowledgeBaseID),
|
||||
// )
|
||||
// }
|
||||
|
||||
// Use shared function to handle KnowledgeQA request
|
||||
h.handleKnowledgeQARequest(ctx, c, session, secutils.SanitizeForLog(request.Query),
|
||||
secutils.SanitizeForLogArray(knowledgeBaseIDs),
|
||||
secutils.SanitizeForLogArray(request.KnowledgeIds),
|
||||
assistantMessage, true, secutils.SanitizeForLog(request.SummaryModelID), request.WebSearchEnabled,
|
||||
convertMentionedItems(request.MentionedItems))
|
||||
// Execute normal mode QA
|
||||
h.executeNormalModeQA(reqCtx, true)
|
||||
}
|
||||
|
||||
// AgentQA godoc
|
||||
@@ -175,427 +361,112 @@ func (h *Handler) KnowledgeQA(c *gin.Context) {
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /sessions/{session_id}/agent-qa [post]
|
||||
func (h *Handler) AgentQA(c *gin.Context) {
|
||||
ctx := logger.CloneContext(c.Request.Context())
|
||||
logger.Info(ctx, "Start processing agent QA request")
|
||||
|
||||
// Get session ID from URL parameter
|
||||
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
|
||||
if sessionID == "" {
|
||||
logger.Error(ctx, "Session ID is empty")
|
||||
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
|
||||
// Parse and validate request
|
||||
reqCtx, request, err := h.parseQARequest(c, "AgentQA")
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var request CreateKnowledgeQARequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
logger.Error(ctx, "Failed to parse request data", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
// Detect and apply configuration changes
|
||||
if _, err := h.detectAndApplyConfigChanges(reqCtx, request); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
if requestJSON, err := json.Marshal(request); err == nil {
|
||||
logger.Infof(ctx, "Agent QA request, request: %s", secutils.SanitizeForLog(string(requestJSON)))
|
||||
|
||||
// Determine if agent mode should be enabled
|
||||
// Priority: customAgent.IsAgentMode() > request.AgentEnabled
|
||||
agentModeEnabled := request.AgentEnabled
|
||||
if reqCtx.customAgent != nil {
|
||||
agentModeEnabled = reqCtx.customAgent.IsAgentMode()
|
||||
logger.Infof(reqCtx.ctx, "Agent mode determined by custom agent: %v (config.agent_mode=%s)",
|
||||
agentModeEnabled, reqCtx.customAgent.Config.AgentMode)
|
||||
}
|
||||
|
||||
// Route to appropriate handler based on agent mode
|
||||
if agentModeEnabled {
|
||||
h.executeAgentModeQA(reqCtx)
|
||||
} else {
|
||||
logger.Warnf(ctx, "failed to marshal for logging: %s", secutils.SanitizeForLog(err.Error()))
|
||||
}
|
||||
|
||||
// Validate query content
|
||||
if request.Query == "" {
|
||||
logger.Error(ctx, "Query content is empty")
|
||||
c.Error(errors.NewBadRequestError("Query content cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
|
||||
// Get session information first
|
||||
session, err := h.sessionService.GetSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
|
||||
c.Error(errors.NewNotFoundError("Session not found"))
|
||||
return
|
||||
}
|
||||
sessionJSON, err := json.Marshal(session)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to marshal session, session ID: %s, error: %v", sessionID, err)
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Before AgentQA, Session: %s", secutils.SanitizeForLog(string(sessionJSON)))
|
||||
|
||||
// Create assistant message
|
||||
assistantMessage := &types.Message{
|
||||
SessionID: sessionID,
|
||||
Role: "assistant",
|
||||
RequestID: c.GetString(types.RequestIDContextKey.String()),
|
||||
IsCompleted: false,
|
||||
}
|
||||
|
||||
// Initialize AgentConfig if it doesn't exist
|
||||
if session.AgentConfig == nil {
|
||||
session.AgentConfig = &types.SessionAgentConfig{}
|
||||
}
|
||||
|
||||
// Detect if knowledge bases or agent mode has changed
|
||||
knowledgeBasesChanged := false
|
||||
knowledgeIdsChanged := false
|
||||
configChanged := false
|
||||
|
||||
// Check if knowledge bases array has changed
|
||||
if len(request.KnowledgeBaseIDs) > 0 || len(session.AgentConfig.KnowledgeBases) > 0 {
|
||||
// Compare arrays to detect changes
|
||||
currentKBs := session.AgentConfig.KnowledgeBases
|
||||
if len(currentKBs) != len(request.KnowledgeBaseIDs) {
|
||||
knowledgeBasesChanged = true
|
||||
configChanged = true
|
||||
} else {
|
||||
// Check if contents are different
|
||||
kbMap := make(map[string]bool)
|
||||
for _, kb := range currentKBs {
|
||||
kbMap[kb] = true
|
||||
}
|
||||
for _, kb := range request.KnowledgeBaseIDs {
|
||||
if !kbMap[kb] {
|
||||
knowledgeBasesChanged = true
|
||||
configChanged = true
|
||||
break
|
||||
}
|
||||
}
|
||||
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 knowledgeBasesChanged {
|
||||
logger.Infof(ctx, "Knowledge bases changed from %s to %s",
|
||||
secutils.SanitizeForLog(fmt.Sprintf("%v", session.AgentConfig.KnowledgeBases)),
|
||||
secutils.SanitizeForLog(fmt.Sprintf("%v", request.KnowledgeBaseIDs)),
|
||||
)
|
||||
if len(reqCtx.knowledgeBaseIDs) == 0 && reqCtx.session.KnowledgeBaseID != "" {
|
||||
reqCtx.knowledgeBaseIDs = []string{reqCtx.session.KnowledgeBaseID}
|
||||
}
|
||||
h.executeNormalModeQA(reqCtx, false)
|
||||
}
|
||||
|
||||
// Check if knowledge IDs array has changed
|
||||
if len(request.KnowledgeIds) > 0 || len(session.AgentConfig.KnowledgeIDs) > 0 {
|
||||
// Compare arrays to detect changes
|
||||
currentKIDs := session.AgentConfig.KnowledgeIDs
|
||||
if len(currentKIDs) != len(request.KnowledgeIds) {
|
||||
knowledgeIdsChanged = true
|
||||
configChanged = true
|
||||
} else {
|
||||
// Check if contents are different
|
||||
kidMap := make(map[string]bool)
|
||||
for _, kid := range currentKIDs {
|
||||
kidMap[kid] = true
|
||||
}
|
||||
for _, kid := range request.KnowledgeIds {
|
||||
if !kidMap[kid] {
|
||||
knowledgeIdsChanged = true
|
||||
configChanged = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if knowledgeIdsChanged {
|
||||
logger.Infof(ctx, "Knowledge IDs changed from %s to %s",
|
||||
secutils.SanitizeForLog(fmt.Sprintf("%v", session.AgentConfig.KnowledgeIDs)),
|
||||
secutils.SanitizeForLog(fmt.Sprintf("%v", request.KnowledgeIds)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Check if agent mode has changed
|
||||
currentAgentEnabled := session.AgentConfig.AgentModeEnabled
|
||||
if request.AgentEnabled != currentAgentEnabled {
|
||||
logger.Infof(ctx, "Agent mode changed from %v to %v", currentAgentEnabled, request.AgentEnabled)
|
||||
configChanged = true
|
||||
}
|
||||
currentWebSearchEnabled := session.AgentConfig.WebSearchEnabled
|
||||
if request.WebSearchEnabled != currentWebSearchEnabled {
|
||||
logger.Infof(ctx, "Web search mode changed from %v to %v", currentWebSearchEnabled, request.WebSearchEnabled)
|
||||
configChanged = true
|
||||
}
|
||||
summaryModelID := secutils.SanitizeForLog(request.SummaryModelID)
|
||||
if summaryModelID == "" {
|
||||
summaryModelID = session.SummaryModelID
|
||||
}
|
||||
if summaryModelID == "" && tenantInfo.ConversationConfig != nil {
|
||||
summaryModelID = tenantInfo.ConversationConfig.SummaryModelID
|
||||
}
|
||||
if summaryModelID != session.SummaryModelID {
|
||||
configChanged = true
|
||||
session.SummaryModelID = summaryModelID
|
||||
}
|
||||
|
||||
// If configuration changed, clear context and update session
|
||||
if configChanged {
|
||||
logger.Warnf(ctx, "Configuration changed, clearing context for session: %s", sessionID)
|
||||
// Clear the LLM context to prevent contamination
|
||||
if err := h.sessionService.ClearContext(ctx, sessionID); err != nil {
|
||||
logger.Errorf(ctx, "Failed to clear context for session %s: %v", sessionID, err)
|
||||
// Continue anyway - this is not a fatal error
|
||||
}
|
||||
if err := h.sessionService.DeleteWebSearchTempKBState(ctx, sessionID); err != nil {
|
||||
logger.Errorf(ctx, "Failed to delete temp knowledge base for session %s: %v", sessionID, err)
|
||||
// Continue anyway - this is not a fatal error
|
||||
}
|
||||
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 = secutils.SanitizeForLog(summaryModelID)
|
||||
// Persist the session changes
|
||||
if err := h.sessionService.UpdateSession(ctx, session); err != nil {
|
||||
logger.Errorf(ctx, "Failed to update session %s: %v", sessionID, err)
|
||||
c.Error(errors.NewInternalServerError("Failed to update session configuration"))
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Session configuration updated successfully for session: %s", sessionID)
|
||||
}
|
||||
|
||||
// If Agent mode is disabled, delegate to KnowledgeQA
|
||||
if !request.AgentEnabled {
|
||||
logger.Infof(ctx, "Agent mode disabled, delegating to KnowledgeQA for session: %s", sessionID)
|
||||
|
||||
// Use knowledge bases from request or session config
|
||||
knowledgeBaseIDs := secutils.SanitizeForLogArray(request.KnowledgeBaseIDs)
|
||||
if len(knowledgeBaseIDs) == 0 {
|
||||
knowledgeBaseIDs = session.AgentConfig.KnowledgeBases
|
||||
}
|
||||
|
||||
// If still empty, use session default knowledge base
|
||||
if len(knowledgeBaseIDs) == 0 && session.KnowledgeBaseID != "" {
|
||||
knowledgeBaseIDs = []string{session.KnowledgeBaseID}
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Using session default knowledge base: %s",
|
||||
secutils.SanitizeForLog(session.KnowledgeBaseID),
|
||||
)
|
||||
}
|
||||
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Delegating to KnowledgeQA with knowledge bases: %s",
|
||||
secutils.SanitizeForLog(fmt.Sprintf("%v", knowledgeBaseIDs)),
|
||||
)
|
||||
|
||||
// Use shared function to handle KnowledgeQA request (no title generation for AgentQA fallback)
|
||||
h.handleKnowledgeQARequest(
|
||||
ctx,
|
||||
c,
|
||||
session,
|
||||
secutils.SanitizeForLog(request.Query),
|
||||
secutils.SanitizeForLogArray(
|
||||
knowledgeBaseIDs,
|
||||
),
|
||||
secutils.SanitizeForLogArray(
|
||||
request.KnowledgeIds,
|
||||
),
|
||||
assistantMessage,
|
||||
false,
|
||||
secutils.SanitizeForLog(request.SummaryModelID),
|
||||
request.WebSearchEnabled,
|
||||
convertMentionedItems(request.MentionedItems),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Emit agent query event to create user message
|
||||
requestID := secutils.SanitizeForLog(c.GetString(types.RequestIDContextKey.String()))
|
||||
if err := event.Emit(ctx, event.Event{
|
||||
Type: event.EventAgentQuery,
|
||||
SessionID: sessionID,
|
||||
RequestID: requestID,
|
||||
Data: event.AgentQueryData{
|
||||
SessionID: sessionID,
|
||||
Query: secutils.SanitizeForLog(request.Query),
|
||||
RequestID: requestID,
|
||||
},
|
||||
}); err != nil {
|
||||
logger.Errorf(ctx, "Failed to emit agent query event: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Set headers for SSE immediately
|
||||
setSSEHeaders(c)
|
||||
|
||||
// Create user message
|
||||
if err := h.createUserMessage(ctx, sessionID, secutils.SanitizeForLog(request.Query), requestID, convertMentionedItems(request.MentionedItems)); err != nil {
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Create assistant message (response)
|
||||
assistantMessagePtr, err := h.createAssistantMessage(ctx, assistantMessage)
|
||||
if err != nil {
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
assistantMessage = assistantMessagePtr
|
||||
|
||||
logger.Infof(ctx, "Calling agent QA service, session ID: %s", sessionID)
|
||||
|
||||
// Write initial agent_query event to StreamManager
|
||||
h.writeAgentQueryEvent(ctx, sessionID, assistantMessage.ID)
|
||||
|
||||
eventBus := event.NewEventBus()
|
||||
// Create cancellable context for async operations
|
||||
asyncCtx, cancel := context.WithCancel(logger.CloneContext(ctx))
|
||||
// Create and subscribe stream handler
|
||||
h.setupStreamHandler(asyncCtx, sessionID, assistantMessage.ID, requestID, assistantMessage, eventBus)
|
||||
|
||||
// Start async title generation if session has no title
|
||||
if session.Title == "" {
|
||||
logger.Infof(ctx, "Session has no title, starting async title generation, session ID: %s", sessionID)
|
||||
h.sessionService.GenerateTitleAsync(asyncCtx, session, secutils.SanitizeForLog(request.Query), eventBus)
|
||||
}
|
||||
|
||||
// Register stop event handler to cancel the context
|
||||
h.setupStopEventHandler(eventBus, sessionID, assistantMessage, cancel)
|
||||
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
buf := make([]byte, 1024)
|
||||
runtime.Stack(buf, true)
|
||||
logger.ErrorWithFields(asyncCtx,
|
||||
errors.NewInternalServerError(fmt.Sprintf("Agent QA service panicked: %v\n%s", r, string(buf))),
|
||||
map[string]interface{}{
|
||||
"session_id": sessionID,
|
||||
})
|
||||
}
|
||||
h.completeAssistantMessage(asyncCtx, assistantMessage)
|
||||
logger.Infof(asyncCtx, "Agent QA service completed for session: %s", sessionID)
|
||||
}()
|
||||
err := h.sessionService.AgentQA(
|
||||
asyncCtx,
|
||||
session,
|
||||
secutils.SanitizeForLog(request.Query),
|
||||
assistantMessage.ID,
|
||||
eventBus,
|
||||
)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(asyncCtx, err, nil)
|
||||
// Emit error event to dedicated EventBus
|
||||
eventBus.Emit(asyncCtx, event.Event{
|
||||
Type: event.EventError,
|
||||
SessionID: sessionID,
|
||||
Data: event.ErrorData{
|
||||
Error: err.Error(),
|
||||
Stage: "agent_execution",
|
||||
SessionID: sessionID,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
// Handle events for SSE (blocking until connection is done)
|
||||
// Wait for title only if session has no title (first message in session)
|
||||
h.handleAgentEventsForSSE(ctx, c, sessionID, assistantMessage.ID, requestID, eventBus, session.Title == "")
|
||||
}
|
||||
|
||||
// handleKnowledgeQARequest handles a KnowledgeQA request with the given parameters
|
||||
// This is a shared function used by both KnowledgeQA endpoint and AgentQA fallback
|
||||
func (h *Handler) handleKnowledgeQARequest(
|
||||
ctx context.Context,
|
||||
c *gin.Context,
|
||||
session *types.Session,
|
||||
query string,
|
||||
knowledgeBaseIDs []string,
|
||||
knowledgeIDs []string,
|
||||
assistantMessage *types.Message,
|
||||
generateTitle bool, // Whether to generate title if session has no title
|
||||
summaryModelID string, // Optional summary model ID (overrides session default)
|
||||
webSearchEnabled bool, // Whether web search is enabled
|
||||
mentionedItems types.MentionedItems, // @mentioned knowledge bases and files
|
||||
) {
|
||||
sessionID := session.ID
|
||||
requestID := getRequestID(c)
|
||||
// executeNormalModeQA executes the normal (KnowledgeQA) mode
|
||||
func (h *Handler) executeNormalModeQA(reqCtx *qaRequestContext, generateTitle bool) {
|
||||
ctx := reqCtx.ctx
|
||||
sessionID := reqCtx.sessionID
|
||||
|
||||
// Create user message
|
||||
if err := h.createUserMessage(ctx, sessionID, query, requestID, mentionedItems); err != nil {
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
if err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems); err != nil {
|
||||
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Create assistant message (response)
|
||||
if _, err := h.createAssistantMessage(ctx, assistantMessage); err != nil {
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
// Create assistant message
|
||||
if _, err := h.createAssistantMessage(ctx, reqCtx.assistantMessage); err != nil {
|
||||
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Using knowledge bases: %s", secutils.SanitizeForLog(fmt.Sprintf("%v", knowledgeBaseIDs)))
|
||||
logger.Infof(ctx, "Using knowledge bases: %v", reqCtx.knowledgeBaseIDs)
|
||||
|
||||
// Set headers for SSE
|
||||
setSSEHeaders(c)
|
||||
// Setup SSE stream
|
||||
streamCtx := h.setupSSEStream(reqCtx)
|
||||
|
||||
// Write initial agent_query event to StreamManager
|
||||
h.writeAgentQueryEvent(ctx, sessionID, assistantMessage.ID)
|
||||
|
||||
// Create dedicated EventBus for this request
|
||||
eventBus := event.NewEventBus()
|
||||
// Create cancellable context for async operations
|
||||
asyncCtx, cancel := context.WithCancel(logger.CloneContext(ctx))
|
||||
|
||||
// Register stop event handler and setup stream handler
|
||||
h.setupStopEventHandler(eventBus, sessionID, assistantMessage, cancel)
|
||||
h.setupStreamHandler(asyncCtx, sessionID, assistantMessage.ID, requestID, assistantMessage, eventBus)
|
||||
|
||||
// Generate title if needed
|
||||
if generateTitle && session.Title == "" {
|
||||
logger.Infof(ctx, "Session has no title, starting async title generation, session ID: %s", sessionID)
|
||||
h.sessionService.GenerateTitleAsync(asyncCtx, session, query, eventBus)
|
||||
}
|
||||
|
||||
eventBus.On(event.EventAgentFinalAnswer, func(ctx context.Context, evt event.Event) error {
|
||||
// Setup completion handler for normal mode
|
||||
streamCtx.eventBus.On(event.EventAgentFinalAnswer, func(ctx context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.AgentFinalAnswerData)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
assistantMessage.Content += data.Content
|
||||
streamCtx.assistantMessage.Content += data.Content
|
||||
if data.Done {
|
||||
logger.Infof(asyncCtx, "Knowledge QA service completed for session: %s", sessionID)
|
||||
h.completeAssistantMessage(asyncCtx, assistantMessage)
|
||||
// Emit completion event when stream finishes
|
||||
if err := eventBus.Emit(asyncCtx, event.Event{
|
||||
logger.Infof(streamCtx.asyncCtx, "Knowledge QA service completed for session: %s", sessionID)
|
||||
h.completeAssistantMessage(streamCtx.asyncCtx, streamCtx.assistantMessage)
|
||||
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
|
||||
Type: event.EventAgentComplete,
|
||||
SessionID: sessionID,
|
||||
Data: event.AgentCompleteData{
|
||||
FinalAnswer: assistantMessage.Content,
|
||||
},
|
||||
}); err != nil {
|
||||
logger.Errorf(asyncCtx, "Failed to emit completion event: %v", err)
|
||||
}
|
||||
cancel() // Clean up context
|
||||
return nil
|
||||
Data: event.AgentCompleteData{FinalAnswer: streamCtx.assistantMessage.Content},
|
||||
})
|
||||
streamCtx.cancel()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
// Call service to perform knowledge QA (async, emits events)
|
||||
// Execute KnowledgeQA asynchronously
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
buf := make([]byte, 10240)
|
||||
runtime.Stack(buf, true)
|
||||
logger.ErrorWithFields(
|
||||
asyncCtx,
|
||||
errors.NewInternalServerError(fmt.Sprintf("Knowledge QA service panicked: %v\n%s", r, string(buf))),
|
||||
nil,
|
||||
)
|
||||
logger.ErrorWithFields(streamCtx.asyncCtx,
|
||||
errors.NewInternalServerError(fmt.Sprintf("Knowledge QA service panicked: %v\n%s", r, string(buf))), nil)
|
||||
}
|
||||
}()
|
||||
|
||||
err := h.sessionService.KnowledgeQA(
|
||||
asyncCtx,
|
||||
session,
|
||||
query,
|
||||
knowledgeBaseIDs,
|
||||
knowledgeIDs,
|
||||
assistantMessage.ID,
|
||||
summaryModelID,
|
||||
webSearchEnabled,
|
||||
eventBus,
|
||||
streamCtx.asyncCtx,
|
||||
reqCtx.session,
|
||||
reqCtx.query,
|
||||
reqCtx.knowledgeBaseIDs,
|
||||
reqCtx.knowledgeIDs,
|
||||
reqCtx.assistantMessage.ID,
|
||||
reqCtx.summaryModelID,
|
||||
reqCtx.webSearchEnabled,
|
||||
streamCtx.eventBus,
|
||||
reqCtx.customAgent,
|
||||
)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(asyncCtx, err, nil)
|
||||
// Emit error event to dedicated EventBus
|
||||
eventBus.Emit(asyncCtx, event.Event{
|
||||
logger.ErrorWithFields(streamCtx.asyncCtx, err, nil)
|
||||
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
|
||||
Type: event.EventError,
|
||||
SessionID: sessionID,
|
||||
Data: event.ErrorData{
|
||||
@@ -604,13 +475,93 @@ func (h *Handler) handleKnowledgeQARequest(
|
||||
SessionID: sessionID,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
}()
|
||||
|
||||
// Handle events for SSE (blocking until connection is done)
|
||||
// Wait for title only if session has no title (first message in session)
|
||||
h.handleAgentEventsForSSE(ctx, c, sessionID, assistantMessage.ID, requestID, eventBus, session.Title == "")
|
||||
// Handle SSE events (blocking)
|
||||
shouldWaitForTitle := generateTitle && reqCtx.session.Title == ""
|
||||
h.handleAgentEventsForSSE(ctx, reqCtx.c, sessionID, reqCtx.assistantMessage.ID,
|
||||
reqCtx.requestID, streamCtx.eventBus, shouldWaitForTitle)
|
||||
}
|
||||
|
||||
// executeAgentModeQA executes the agent mode
|
||||
func (h *Handler) executeAgentModeQA(reqCtx *qaRequestContext) {
|
||||
ctx := reqCtx.ctx
|
||||
sessionID := reqCtx.sessionID
|
||||
|
||||
// Emit agent query event
|
||||
if err := event.Emit(ctx, event.Event{
|
||||
Type: event.EventAgentQuery,
|
||||
SessionID: sessionID,
|
||||
RequestID: reqCtx.requestID,
|
||||
Data: event.AgentQueryData{
|
||||
SessionID: sessionID,
|
||||
Query: reqCtx.query,
|
||||
RequestID: reqCtx.requestID,
|
||||
},
|
||||
}); err != nil {
|
||||
logger.Errorf(ctx, "Failed to emit agent query event: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Create user message
|
||||
if err := h.createUserMessage(ctx, sessionID, reqCtx.query, reqCtx.requestID, reqCtx.mentionedItems); err != nil {
|
||||
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// Create assistant message
|
||||
assistantMessagePtr, err := h.createAssistantMessage(ctx, reqCtx.assistantMessage)
|
||||
if err != nil {
|
||||
reqCtx.c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
reqCtx.assistantMessage = assistantMessagePtr
|
||||
|
||||
logger.Infof(ctx, "Calling agent QA service, session ID: %s", sessionID)
|
||||
|
||||
// Setup SSE stream
|
||||
streamCtx := h.setupSSEStream(reqCtx)
|
||||
|
||||
// Execute AgentQA asynchronously
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
buf := make([]byte, 1024)
|
||||
runtime.Stack(buf, true)
|
||||
logger.ErrorWithFields(streamCtx.asyncCtx,
|
||||
errors.NewInternalServerError(fmt.Sprintf("Agent QA service panicked: %v\n%s", r, string(buf))),
|
||||
map[string]interface{}{"session_id": sessionID})
|
||||
}
|
||||
h.completeAssistantMessage(streamCtx.asyncCtx, streamCtx.assistantMessage)
|
||||
logger.Infof(streamCtx.asyncCtx, "Agent QA service completed for session: %s", sessionID)
|
||||
}()
|
||||
|
||||
err := h.sessionService.AgentQA(
|
||||
streamCtx.asyncCtx,
|
||||
reqCtx.session,
|
||||
reqCtx.query,
|
||||
reqCtx.assistantMessage.ID,
|
||||
streamCtx.eventBus,
|
||||
reqCtx.customAgent,
|
||||
)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(streamCtx.asyncCtx, err, nil)
|
||||
streamCtx.eventBus.Emit(streamCtx.asyncCtx, event.Event{
|
||||
Type: event.EventError,
|
||||
SessionID: sessionID,
|
||||
Data: event.ErrorData{
|
||||
Error: err.Error(),
|
||||
Stage: "agent_execution",
|
||||
SessionID: sessionID,
|
||||
},
|
||||
})
|
||||
}
|
||||
}()
|
||||
|
||||
// Handle SSE events (blocking)
|
||||
h.handleAgentEventsForSSE(ctx, reqCtx.c, sessionID, reqCtx.assistantMessage.ID,
|
||||
reqCtx.requestID, streamCtx.eventBus, reqCtx.session.Title == "")
|
||||
}
|
||||
|
||||
// completeAssistantMessage marks an assistant message as complete and updates it
|
||||
|
||||
@@ -65,6 +65,7 @@ type CreateKnowledgeQARequest struct {
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request
|
||||
KnowledgeIds []string `json:"knowledge_ids"` // Selected knowledge ID for this request
|
||||
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
|
||||
AgentID string `json:"agent_id"` // Selected custom agent ID for this request
|
||||
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
|
||||
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
|
||||
MentionedItems []MentionedItemRequest `json:"mentioned_items"` // @mentioned knowledge bases and files
|
||||
|
||||
@@ -199,12 +199,23 @@ func (c *RemoteAPIChat) buildChatCompletionRequest(messages []Message,
|
||||
"enable_thinking": thinking,
|
||||
}
|
||||
|
||||
// print req
|
||||
// jsonData, err := json.Marshal(req)
|
||||
// if err != nil {
|
||||
// logger.Error(context.Background(), "marshal request: %w", err)
|
||||
// }
|
||||
// logger.Infof(context.Background(), "llm request: %s", string(jsonData))
|
||||
// Log LLM request for debugging
|
||||
if jsonData, err := json.MarshalIndent(req, "", " "); err == nil {
|
||||
logger.Infof(context.Background(), "[LLM Request] model=%s, stream=%v, request:\n%s", c.modelName, isStream, string(jsonData))
|
||||
}
|
||||
|
||||
// Log tools/functions separately for clarity
|
||||
if len(req.Tools) > 0 {
|
||||
toolNames := make([]string, 0, len(req.Tools))
|
||||
for _, tool := range req.Tools {
|
||||
toolNames = append(toolNames, tool.Function.Name)
|
||||
}
|
||||
logger.Infof(context.Background(), "[LLM Request] tools_count=%d, tool_names=%v", len(req.Tools), toolNames)
|
||||
// Print full tool definitions
|
||||
if toolsJSON, err := json.MarshalIndent(req.Tools, "", " "); err == nil {
|
||||
logger.Infof(context.Background(), "[LLM Request] tools_definition:\n%s", string(toolsJSON))
|
||||
}
|
||||
}
|
||||
|
||||
return req
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ type RouterParams struct {
|
||||
WebSearchHandler *handler.WebSearchHandler
|
||||
FAQHandler *handler.FAQHandler
|
||||
TagHandler *handler.TagHandler
|
||||
CustomAgentHandler *handler.CustomAgentHandler
|
||||
}
|
||||
|
||||
// NewRouter 创建新的路由
|
||||
@@ -110,6 +111,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
RegisterSystemRoutes(v1, params.SystemHandler)
|
||||
RegisterMCPServiceRoutes(v1, params.MCPServiceHandler)
|
||||
RegisterWebSearchRoutes(v1, params.WebSearchHandler)
|
||||
RegisterCustomAgentRoutes(v1, params.CustomAgentHandler)
|
||||
}
|
||||
|
||||
return r
|
||||
@@ -410,3 +412,20 @@ func RegisterWebSearchRoutes(r *gin.RouterGroup, webSearchHandler *handler.WebSe
|
||||
webSearch.GET("/providers", webSearchHandler.GetProviders)
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterCustomAgentRoutes registers custom agent routes
|
||||
func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAgentHandler) {
|
||||
agents := r.Group("/agents")
|
||||
{
|
||||
// Create custom agent
|
||||
agents.POST("", agentHandler.CreateAgent)
|
||||
// List all agents (including built-in)
|
||||
agents.GET("", agentHandler.ListAgents)
|
||||
// Get agent by ID
|
||||
agents.GET("/:id", agentHandler.GetAgent)
|
||||
// Update agent
|
||||
agents.PUT("/:id", agentHandler.UpdateAgent)
|
||||
// Delete agent
|
||||
agents.DELETE("/:id", agentHandler.DeleteAgent)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,8 @@ type AgentConfig struct {
|
||||
UseCustomSystemPrompt bool `json:"use_custom_system_prompt"` // Whether to use custom system prompt instead of default
|
||||
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search tool is enabled
|
||||
WebSearchMaxResults int `json:"web_search_max_results"` // Maximum number of web search results (default: 5)
|
||||
MultiTurnEnabled bool `json:"multi_turn_enabled"` // Whether multi-turn conversation is enabled
|
||||
HistoryTurns int `json:"history_turns"` // Number of history turns to keep in context
|
||||
SearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CustomAgentType represents the type of the custom agent
|
||||
type CustomAgentType string
|
||||
|
||||
const (
|
||||
// CustomAgentTypeNormal represents the normal RAG-based chat mode
|
||||
CustomAgentTypeNormal CustomAgentType = "normal"
|
||||
// CustomAgentTypeAgent represents the ReAct agent mode with tool calling
|
||||
CustomAgentTypeAgent CustomAgentType = "agent"
|
||||
// CustomAgentTypeCustom represents user-defined custom agents
|
||||
CustomAgentTypeCustom CustomAgentType = "custom"
|
||||
)
|
||||
|
||||
// BuiltinAgentID constants for built-in agents
|
||||
const (
|
||||
BuiltinAgentNormalID = "builtin-normal"
|
||||
BuiltinAgentAgentID = "builtin-agent"
|
||||
)
|
||||
|
||||
// CustomAgent represents a configurable AI agent (similar to GPTs)
|
||||
type CustomAgent struct {
|
||||
// Unique identifier of the agent
|
||||
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"`
|
||||
// Name of the agent
|
||||
Name string `yaml:"name" json:"name" gorm:"type:varchar(255);not null"`
|
||||
// Description of the agent
|
||||
Description string `yaml:"description" json:"description" gorm:"type:text"`
|
||||
// Avatar/Icon of the agent (emoji or icon name)
|
||||
Avatar string `yaml:"avatar" json:"avatar" gorm:"type:varchar(64)"`
|
||||
// Whether this is a built-in agent (normal mode / agent mode)
|
||||
IsBuiltin bool `yaml:"is_builtin" json:"is_builtin" gorm:"default:false"`
|
||||
// Type of the agent: normal, agent, custom
|
||||
Type CustomAgentType `yaml:"type" json:"type" gorm:"type:varchar(32);default:'custom'"`
|
||||
// Tenant ID
|
||||
TenantID uint64 `yaml:"tenant_id" json:"tenant_id" gorm:"index"`
|
||||
// Created by user ID
|
||||
CreatedBy string `yaml:"created_by" json:"created_by" gorm:"type:varchar(36)"`
|
||||
|
||||
// Agent configuration
|
||||
Config CustomAgentConfig `yaml:"config" json:"config" gorm:"type:json"`
|
||||
|
||||
// Timestamps
|
||||
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `yaml:"deleted_at" json:"deleted_at" gorm:"index"`
|
||||
}
|
||||
|
||||
// CustomAgentConfig represents the configuration of a custom agent
|
||||
type CustomAgentConfig struct {
|
||||
// Agent mode: "normal" for RAG mode, "agent" for ReAct agent mode
|
||||
AgentMode string `yaml:"agent_mode" json:"agent_mode"`
|
||||
// System prompt for the agent
|
||||
SystemPrompt string `yaml:"system_prompt" json:"system_prompt"`
|
||||
// Model ID to use for conversations
|
||||
ModelID string `yaml:"model_id" json:"model_id"`
|
||||
// Temperature for LLM (0-1)
|
||||
Temperature float64 `yaml:"temperature" json:"temperature"`
|
||||
// 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
|
||||
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
|
||||
AllowUserKBSelection *bool `yaml:"allow_user_kb_selection" json:"allow_user_kb_selection"`
|
||||
// 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
|
||||
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"`
|
||||
}
|
||||
|
||||
// Value implements driver.Valuer interface for CustomAgentConfig
|
||||
func (c CustomAgentConfig) Value() (driver.Value, error) {
|
||||
return json.Marshal(c)
|
||||
}
|
||||
|
||||
// Scan implements sql.Scanner interface for CustomAgentConfig
|
||||
func (c *CustomAgentConfig) Scan(value interface{}) error {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
b, ok := value.([]byte)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(b, c)
|
||||
}
|
||||
|
||||
// TableName returns the table name for CustomAgent
|
||||
func (CustomAgent) TableName() string {
|
||||
return "custom_agents"
|
||||
}
|
||||
|
||||
// EnsureDefaults sets default values for the agent
|
||||
func (a *CustomAgent) EnsureDefaults() {
|
||||
if a == nil {
|
||||
return
|
||||
}
|
||||
if a.Type == "" {
|
||||
a.Type = CustomAgentTypeCustom
|
||||
}
|
||||
if a.Config.Temperature == 0 {
|
||||
a.Config.Temperature = 0.7
|
||||
}
|
||||
if a.Config.MaxIterations == 0 {
|
||||
a.Config.MaxIterations = 10
|
||||
}
|
||||
if a.Config.WebSearchMaxResults == 0 {
|
||||
a.Config.WebSearchMaxResults = 5
|
||||
}
|
||||
if a.Config.HistoryTurns == 0 {
|
||||
a.Config.HistoryTurns = 5
|
||||
}
|
||||
}
|
||||
|
||||
// IsAgentMode returns true if this agent uses ReAct agent mode
|
||||
func (a *CustomAgent) IsAgentMode() bool {
|
||||
return a.Config.AgentMode == "agent"
|
||||
}
|
||||
|
||||
// GetBuiltinNormalAgent returns the built-in normal mode agent
|
||||
func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {
|
||||
return &CustomAgent{
|
||||
ID: BuiltinAgentNormalID,
|
||||
Name: "普通模式",
|
||||
Description: "基于知识库的 RAG 问答,快速准确地回答问题",
|
||||
Avatar: "💬",
|
||||
IsBuiltin: true,
|
||||
Type: CustomAgentTypeNormal,
|
||||
TenantID: tenantID,
|
||||
Config: CustomAgentConfig{
|
||||
AgentMode: "normal",
|
||||
SystemPrompt: "",
|
||||
Temperature: 0.7,
|
||||
WebSearchEnabled: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// GetBuiltinAgentAgent returns the built-in agent mode agent
|
||||
func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
|
||||
return &CustomAgent{
|
||||
ID: BuiltinAgentAgentID,
|
||||
Name: "Agent 模式",
|
||||
Description: "ReAct 推理框架,支持多步思考和工具调用",
|
||||
Avatar: "🤖",
|
||||
IsBuiltin: true,
|
||||
Type: CustomAgentTypeAgent,
|
||||
TenantID: tenantID,
|
||||
Config: CustomAgentConfig{
|
||||
AgentMode: "agent",
|
||||
SystemPrompt: "",
|
||||
Temperature: 0.7,
|
||||
MaxIterations: 10,
|
||||
AllowedTools: []string{"knowledge_search", "web_search"},
|
||||
WebSearchEnabled: true,
|
||||
WebSearchMaxResults: 5,
|
||||
ReflectionEnabled: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// GetBuiltinAgents returns all built-in agents for a tenant
|
||||
func GetBuiltinAgents(tenantID uint64) []*CustomAgent {
|
||||
return []*CustomAgent{
|
||||
GetBuiltinNormalAgent(tenantID),
|
||||
GetBuiltinAgentAgent(tenantID),
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,10 @@ type ContextManager interface {
|
||||
|
||||
// GetContextStats returns statistics about the context
|
||||
GetContextStats(ctx context.Context, sessionID string) (*ContextStats, error)
|
||||
|
||||
// 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
|
||||
SetSystemPrompt(ctx context.Context, sessionID string, systemPrompt string) error
|
||||
}
|
||||
|
||||
// ContextStats contains statistics about session context
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// Package interfaces defines the interface contracts for custom agent management
|
||||
package interfaces
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// CustomAgentService defines the custom agent service interface
|
||||
// Provides high-level operations for agent creation, querying, updating, and deletion
|
||||
type CustomAgentService interface {
|
||||
// CreateAgent creates a new custom agent
|
||||
// Parameters:
|
||||
// - ctx: Context information, carrying request tracking, user identity, etc.
|
||||
// - agent: Agent object containing basic information and configuration
|
||||
// Returns:
|
||||
// - Created agent object (including automatically generated ID)
|
||||
// - Possible errors such as insufficient permissions, validation errors, etc.
|
||||
CreateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error)
|
||||
|
||||
// GetAgentByID retrieves agent information by ID
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - id: Unique identifier of the agent
|
||||
// Returns:
|
||||
// - Agent object, if found (including built-in agents)
|
||||
// - Possible errors such as not existing, insufficient permissions, etc.
|
||||
GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error)
|
||||
|
||||
// ListAgents lists all agents under the current tenant (including built-in agents)
|
||||
// Parameters:
|
||||
// - ctx: Context information, containing tenant information
|
||||
// Returns:
|
||||
// - List of agent objects (built-in agents first, then custom agents sorted by creation time)
|
||||
// - Possible errors such as insufficient permissions, etc.
|
||||
ListAgents(ctx context.Context) ([]*types.CustomAgent, error)
|
||||
|
||||
// UpdateAgent updates agent information
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - agent: Agent object containing update information
|
||||
// Returns:
|
||||
// - Updated agent object
|
||||
// - Possible errors such as not existing, insufficient permissions, cannot modify built-in, etc.
|
||||
UpdateAgent(ctx context.Context, agent *types.CustomAgent) (*types.CustomAgent, error)
|
||||
|
||||
// DeleteAgent deletes an agent
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - id: Unique identifier of the agent
|
||||
// Returns:
|
||||
// - Possible errors such as not existing, insufficient permissions, cannot delete built-in, etc.
|
||||
DeleteAgent(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// CustomAgentRepository defines the custom agent repository interface
|
||||
// Responsible for agent data persistence and retrieval
|
||||
type CustomAgentRepository interface {
|
||||
// CreateAgent creates an agent record
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - agent: Agent object
|
||||
// Returns:
|
||||
// - 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
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - id: Agent ID
|
||||
// Returns:
|
||||
// - Agent object, if found
|
||||
// - Possible errors such as record not existing, database errors, etc.
|
||||
GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error)
|
||||
|
||||
// ListAgentsByTenantID lists all agents for a specific tenant
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - tenantID: Tenant ID
|
||||
// Returns:
|
||||
// - List of agent objects
|
||||
// - Possible errors such as database errors, etc.
|
||||
ListAgentsByTenantID(ctx context.Context, tenantID uint64) ([]*types.CustomAgent, error)
|
||||
|
||||
// UpdateAgent updates an agent record
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - agent: Agent object containing update information
|
||||
// Returns:
|
||||
// - Possible errors such as record not existing, database errors, etc.
|
||||
UpdateAgent(ctx context.Context, agent *types.CustomAgent) error
|
||||
|
||||
// DeleteAgent deletes an agent record
|
||||
// Parameters:
|
||||
// - ctx: Context information
|
||||
// - id: Agent ID
|
||||
// Returns:
|
||||
// - Possible errors such as record not existing, database errors, etc.
|
||||
DeleteAgent(ctx context.Context, id string) error
|
||||
}
|
||||
@@ -31,10 +31,12 @@ type SessionService interface {
|
||||
// knowledgeIDs: list of specific knowledge (file) IDs to search
|
||||
// summaryModelID: optional summary model ID override (if empty, uses session/KB default)
|
||||
// webSearchEnabled: whether to enable web search to supplement knowledge base results
|
||||
// customAgent: optional custom agent for config override (multiTurnEnabled, historyTurns)
|
||||
// Events are emitted through eventBus (references, answer chunks, completion)
|
||||
KnowledgeQA(ctx context.Context,
|
||||
session *types.Session, query string, knowledgeBaseIDs []string, knowledgeIDs []string,
|
||||
assistantMessageID string, summaryModelID string, webSearchEnabled bool, eventBus *event.EventBus,
|
||||
customAgent *types.CustomAgent,
|
||||
) error
|
||||
// KnowledgeQAByEvent performs knowledge-based question answering by event
|
||||
KnowledgeQAByEvent(ctx context.Context, chatManage *types.ChatManage, eventList []types.EventType) error
|
||||
@@ -42,12 +44,14 @@ type SessionService interface {
|
||||
SearchKnowledge(ctx context.Context, knowledgeBaseID, query string) ([]*types.SearchResult, error)
|
||||
// AgentQA performs agent-based question answering with conversation history and streaming support
|
||||
// eventBus is optional - if nil, uses service's default EventBus
|
||||
// customAgent is optional - if provided, uses custom agent configuration instead of tenant defaults
|
||||
AgentQA(
|
||||
ctx context.Context,
|
||||
session *types.Session,
|
||||
query string,
|
||||
assistantMessageID string,
|
||||
eventBus *event.EventBus,
|
||||
customAgent *types.CustomAgent,
|
||||
) error
|
||||
// ClearContext clears the LLM context for a session
|
||||
ClearContext(ctx context.Context, sessionID string) error
|
||||
|
||||
Reference in New Issue
Block a user