refactor: 调整智能体配置,增强智能体选择与状态管理
This commit is contained in:
@@ -57,6 +57,6 @@ func (r *customAgentRepository) UpdateAgent(ctx context.Context, agent *types.Cu
|
||||
}
|
||||
|
||||
// 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
|
||||
func (r *customAgentRepository) DeleteAgent(ctx context.Context, id string, tenantID uint64) error {
|
||||
return r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).Delete(&types.CustomAgent{}).Error
|
||||
}
|
||||
|
||||
@@ -101,25 +101,51 @@ func (s *agentService) CreateAgentEngine(
|
||||
tenantID = tid
|
||||
}
|
||||
if tenantID > 0 && s.mcpServiceService != nil && s.mcpManager != nil {
|
||||
// Get enabled MCP services for this tenant
|
||||
mcpServices, err := s.mcpServiceService.ListMCPServices(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list MCP services: %v", err)
|
||||
// Check MCP selection mode from agent config
|
||||
mcpMode := config.MCPSelectionMode
|
||||
if mcpMode == "" {
|
||||
mcpMode = "all" // Default to all enabled MCP services
|
||||
}
|
||||
|
||||
// Skip MCP registration if mode is "none"
|
||||
if mcpMode == "none" {
|
||||
logger.Infof(ctx, "MCP services disabled by agent config (mode: none)")
|
||||
} else {
|
||||
// Filter enabled services
|
||||
enabledServices := make([]*types.MCPService, 0)
|
||||
for _, svc := range mcpServices {
|
||||
if svc != nil && svc.Enabled {
|
||||
enabledServices = append(enabledServices, svc)
|
||||
var mcpServices []*types.MCPService
|
||||
var err error
|
||||
|
||||
if mcpMode == "selected" && len(config.MCPServices) > 0 {
|
||||
// Get only selected MCP services
|
||||
mcpServices, err = s.mcpServiceService.ListMCPServicesByIDs(ctx, tenantID, config.MCPServices)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list selected MCP services: %v", err)
|
||||
} else {
|
||||
logger.Infof(ctx, "Using %d selected MCP services from agent config", len(mcpServices))
|
||||
}
|
||||
} else {
|
||||
// Get all MCP services for this tenant
|
||||
mcpServices, err = s.mcpServiceService.ListMCPServices(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to list MCP services: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Register MCP tools
|
||||
if len(enabledServices) > 0 {
|
||||
if err := tools.RegisterMCPTools(ctx, toolRegistry, enabledServices, s.mcpManager); err != nil {
|
||||
logger.Warnf(ctx, "Failed to register MCP tools: %v", err)
|
||||
} else {
|
||||
logger.Infof(ctx, "Registered MCP tools from %d enabled services", len(enabledServices))
|
||||
if err == nil && len(mcpServices) > 0 {
|
||||
// Filter enabled services
|
||||
enabledServices := make([]*types.MCPService, 0)
|
||||
for _, svc := range mcpServices {
|
||||
if svc != nil && svc.Enabled {
|
||||
enabledServices = append(enabledServices, svc)
|
||||
}
|
||||
}
|
||||
|
||||
// Register MCP tools
|
||||
if len(enabledServices) > 0 {
|
||||
if err := tools.RegisterMCPTools(ctx, toolRegistry, enabledServices, s.mcpManager); err != nil {
|
||||
logger.Warnf(ctx, "Failed to register MCP tools: %v", err)
|
||||
} else {
|
||||
logger.Infof(ctx, "Registered MCP tools from %d enabled services", len(enabledServices))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,13 +60,8 @@ func prepareMessagesWithHistory(chatManage *types.ChatManage) []chat.Message {
|
||||
{Role: "system", Content: systemPrompt},
|
||||
}
|
||||
|
||||
chatHistory := chatManage.History
|
||||
if len(chatHistory) > 2 {
|
||||
chatHistory = chatHistory[len(chatHistory)-2:]
|
||||
}
|
||||
|
||||
// Add conversation history
|
||||
for _, history := range chatHistory {
|
||||
// Add conversation history (already limited by maxRounds in load_history/rewrite plugins)
|
||||
for _, history := range chatManage.History {
|
||||
chatMessages = append(chatMessages, chat.Message{Role: "user", Content: history.Query})
|
||||
chatMessages = append(chatMessages, chat.Message{Role: "assistant", Content: history.Answer})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// Package chatpipline provides chat pipeline processing capabilities
|
||||
package chatpipline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// PluginLoadHistory is a plugin for loading conversation history without query rewriting
|
||||
// It loads historical dialog context for multi-turn conversations
|
||||
type PluginLoadHistory struct {
|
||||
messageService interfaces.MessageService // Message service for retrieving historical messages
|
||||
config *config.Config // System configuration
|
||||
}
|
||||
|
||||
// regThink is a regular expression used to match and remove content between <think></think> tags
|
||||
var regThink = regexp.MustCompile(`(?s)<think>.*?</think>`)
|
||||
|
||||
// NewPluginLoadHistory creates a new history loading plugin instance
|
||||
// Also registers the plugin with the event manager
|
||||
func NewPluginLoadHistory(eventManager *EventManager,
|
||||
messageService interfaces.MessageService,
|
||||
config *config.Config,
|
||||
) *PluginLoadHistory {
|
||||
res := &PluginLoadHistory{
|
||||
messageService: messageService,
|
||||
config: config,
|
||||
}
|
||||
eventManager.Register(res)
|
||||
return res
|
||||
}
|
||||
|
||||
// ActivationEvents returns the list of event types this plugin responds to
|
||||
// This plugin only responds to LOAD_HISTORY events
|
||||
func (p *PluginLoadHistory) ActivationEvents() []types.EventType {
|
||||
return []types.EventType{types.LOAD_HISTORY}
|
||||
}
|
||||
|
||||
// OnEvent processes triggered events
|
||||
// When receiving a LOAD_HISTORY event, it loads conversation history without rewriting the query
|
||||
func (p *PluginLoadHistory) OnEvent(ctx context.Context,
|
||||
eventType types.EventType, chatManage *types.ChatManage, next func() *PluginError,
|
||||
) *PluginError {
|
||||
// Determine max rounds from config or request
|
||||
maxRounds := p.config.Conversation.MaxRounds
|
||||
if chatManage.MaxRounds > 0 {
|
||||
maxRounds = chatManage.MaxRounds
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "LoadHistory", "input", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"max_rounds": maxRounds,
|
||||
})
|
||||
|
||||
// Get conversation history (fetch more to account for incomplete pairs)
|
||||
history, err := p.messageService.GetRecentMessagesBySession(ctx, chatManage.SessionID, maxRounds*2+10)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "LoadHistory", "history_fetch", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return next()
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "LoadHistory", "fetched", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"message_count": len(history),
|
||||
})
|
||||
|
||||
// Convert historical messages to conversation history structure
|
||||
historyMap := make(map[string]*types.History)
|
||||
|
||||
// Process historical messages, grouped by requestID
|
||||
for _, message := range history {
|
||||
h, ok := historyMap[message.RequestID]
|
||||
if !ok {
|
||||
h = &types.History{}
|
||||
}
|
||||
if message.Role == "user" {
|
||||
// User message as query
|
||||
h.Query = message.Content
|
||||
h.CreateAt = message.CreatedAt
|
||||
} else {
|
||||
// System message as answer, while removing thinking process
|
||||
h.Answer = regThink.ReplaceAllString(message.Content, "")
|
||||
h.KnowledgeReferences = message.KnowledgeReferences
|
||||
}
|
||||
historyMap[message.RequestID] = h
|
||||
}
|
||||
|
||||
// Convert to list and filter incomplete conversations
|
||||
historyList := make([]*types.History, 0)
|
||||
for _, h := range historyMap {
|
||||
if h.Answer != "" && h.Query != "" {
|
||||
historyList = append(historyList, h)
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by time, keep the most recent conversations
|
||||
sort.Slice(historyList, func(i, j int) bool {
|
||||
return historyList[i].CreateAt.After(historyList[j].CreateAt)
|
||||
})
|
||||
|
||||
// Limit the number of historical records
|
||||
if len(historyList) > maxRounds {
|
||||
historyList = historyList[:maxRounds]
|
||||
}
|
||||
|
||||
// Reverse to chronological order
|
||||
slices.Reverse(historyList)
|
||||
chatManage.History = historyList
|
||||
|
||||
pipelineInfo(ctx, "LoadHistory", "output", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"history_rounds": len(historyList),
|
||||
"max_rounds": maxRounds,
|
||||
})
|
||||
|
||||
return next()
|
||||
}
|
||||
@@ -3,12 +3,11 @@
|
||||
package chatpipline
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"html/template"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
@@ -144,54 +143,27 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,
|
||||
if chatManage.RewritePromptUser != "" {
|
||||
userPrompt = chatManage.RewritePromptUser
|
||||
}
|
||||
userTmpl, err := template.New("rewriteContent").Parse(userPrompt)
|
||||
if err != nil {
|
||||
pipelineError(ctx, "Rewrite", "parse_user_template", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return next()
|
||||
}
|
||||
systemPrompt := p.config.Conversation.RewritePromptSystem
|
||||
if chatManage.RewritePromptSystem != "" {
|
||||
systemPrompt = chatManage.RewritePromptSystem
|
||||
}
|
||||
systemTmpl, err := template.New("rewriteContent").Parse(systemPrompt)
|
||||
if err != nil {
|
||||
pipelineError(ctx, "Rewrite", "parse_system_template", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return next()
|
||||
}
|
||||
|
||||
// Format conversation history for template
|
||||
conversationText := formatConversationHistory(historyList)
|
||||
currentTime := time.Now().Format("2006-01-02 15:04:05")
|
||||
var userContent, systemContent bytes.Buffer
|
||||
err = userTmpl.Execute(&userContent, map[string]interface{}{
|
||||
"Query": chatManage.Query,
|
||||
"CurrentTime": currentTime,
|
||||
"Yesterday": time.Now().AddDate(0, 0, -1).Format("2006-01-02"),
|
||||
"Conversation": historyList,
|
||||
})
|
||||
if err != nil {
|
||||
pipelineError(ctx, "Rewrite", "render_user_template", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return next()
|
||||
}
|
||||
err = systemTmpl.Execute(&systemContent, map[string]interface{}{
|
||||
"Query": chatManage.Query,
|
||||
"CurrentTime": currentTime,
|
||||
"Yesterday": time.Now().AddDate(0, 0, -1).Format("2006-01-02"),
|
||||
"Conversation": historyList,
|
||||
})
|
||||
if err != nil {
|
||||
pipelineError(ctx, "Rewrite", "render_system_template", map[string]interface{}{
|
||||
"session_id": chatManage.SessionID,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return next()
|
||||
}
|
||||
yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
|
||||
|
||||
// Replace placeholders in prompts
|
||||
userContent := strings.ReplaceAll(userPrompt, "{{conversation}}", conversationText)
|
||||
userContent = strings.ReplaceAll(userContent, "{{query}}", chatManage.Query)
|
||||
userContent = strings.ReplaceAll(userContent, "{{current_time}}", currentTime)
|
||||
userContent = strings.ReplaceAll(userContent, "{{yesterday}}", yesterday)
|
||||
|
||||
systemContent := strings.ReplaceAll(systemPrompt, "{{conversation}}", conversationText)
|
||||
systemContent = strings.ReplaceAll(systemContent, "{{query}}", chatManage.Query)
|
||||
systemContent = strings.ReplaceAll(systemContent, "{{current_time}}", currentTime)
|
||||
systemContent = strings.ReplaceAll(systemContent, "{{yesterday}}", yesterday)
|
||||
|
||||
rewriteModel, err := p.modelService.GetChatModel(ctx, chatManage.ChatModelID)
|
||||
if err != nil {
|
||||
pipelineError(ctx, "Rewrite", "get_model", map[string]interface{}{
|
||||
@@ -207,11 +179,11 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,
|
||||
response, err := rewriteModel.Chat(ctx, []chat.Message{
|
||||
{
|
||||
Role: "system",
|
||||
Content: systemContent.String(),
|
||||
Content: systemContent,
|
||||
},
|
||||
{
|
||||
Role: "user",
|
||||
Content: userContent.String(),
|
||||
Content: userContent,
|
||||
},
|
||||
}, &chat.ChatOptions{
|
||||
Temperature: 0.3,
|
||||
@@ -236,3 +208,21 @@ func (p *PluginRewrite) OnEvent(ctx context.Context,
|
||||
})
|
||||
return next()
|
||||
}
|
||||
|
||||
// formatConversationHistory formats conversation history for prompt template
|
||||
func formatConversationHistory(historyList []*types.History) string {
|
||||
if len(historyList) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
for _, h := range historyList {
|
||||
builder.WriteString("------BEGIN------\n")
|
||||
builder.WriteString("用户的问题是:")
|
||||
builder.WriteString(h.Query)
|
||||
builder.WriteString("\n助手的回答是:")
|
||||
builder.WriteString(h.Answer)
|
||||
builder.WriteString("\n------END------\n")
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
@@ -56,9 +56,9 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo
|
||||
agent.CreatedAt = time.Now()
|
||||
agent.UpdatedAt = time.Now()
|
||||
|
||||
// Ensure custom type for user-created agents
|
||||
if agent.Type == "" {
|
||||
agent.Type = types.CustomAgentTypeCustom
|
||||
// Ensure agent mode is set for user-created agents
|
||||
if agent.Config.AgentMode == "" {
|
||||
agent.Config.AgentMode = types.AgentModeQuickAnswer
|
||||
}
|
||||
|
||||
// Cannot create built-in agents
|
||||
@@ -67,8 +67,8 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo
|
||||
// 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)
|
||||
logger.Infof(ctx, "Creating custom agent, ID: %s, tenant ID: %d, name: %s, agent_mode: %s",
|
||||
agent.ID, agent.TenantID, agent.Name, agent.Config.AgentMode)
|
||||
|
||||
if err := s.repo.CreateAgent(ctx, agent); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
@@ -95,19 +95,18 @@ func (s *customAgentService) GetAgentByID(ctx context.Context, id string) (*type
|
||||
return nil, ErrInvalidTenantID
|
||||
}
|
||||
|
||||
// Check if it's a built-in agent
|
||||
if id == types.BuiltinAgentNormalID || id == types.BuiltinAgentAgentID {
|
||||
// Check if it's a built-in agent using the registry
|
||||
if types.IsBuiltinAgentID(id) {
|
||||
// Try to get from database first (for customized config)
|
||||
agent, err := s.repo.GetAgentByID(ctx, id, tenantID)
|
||||
if err == nil {
|
||||
// Found in database, return with customized config
|
||||
return agent, nil
|
||||
}
|
||||
// Not in database, return default built-in agent
|
||||
if id == types.BuiltinAgentNormalID {
|
||||
return types.GetBuiltinNormalAgent(tenantID), nil
|
||||
// Not in database, return default built-in agent from registry
|
||||
if builtinAgent := types.GetBuiltinAgent(id, tenantID); builtinAgent != nil {
|
||||
return builtinAgent, nil
|
||||
}
|
||||
return types.GetBuiltinAgentAgent(tenantID), nil
|
||||
}
|
||||
|
||||
// Query from database
|
||||
@@ -141,48 +140,39 @@ func (s *customAgentService) ListAgents(ctx context.Context) ([]*types.CustomAge
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if built-in agents exist in database
|
||||
hasNormalBuiltin := false
|
||||
hasAgentBuiltin := false
|
||||
// Track which built-in agents exist in database
|
||||
builtinInDB := make(map[string]bool)
|
||||
for _, agent := range allAgents {
|
||||
if agent.ID == types.BuiltinAgentNormalID {
|
||||
hasNormalBuiltin = true
|
||||
}
|
||||
if agent.ID == types.BuiltinAgentAgentID {
|
||||
hasAgentBuiltin = true
|
||||
if types.IsBuiltinAgentID(agent.ID) {
|
||||
builtinInDB[agent.ID] = true
|
||||
}
|
||||
}
|
||||
|
||||
// Build result: built-in agents first, then custom agents
|
||||
result := make([]*types.CustomAgent, 0, len(allAgents)+2)
|
||||
builtinIDs := types.GetBuiltinAgentIDs()
|
||||
result := make([]*types.CustomAgent, 0, len(allAgents)+len(builtinIDs))
|
||||
|
||||
// Add built-in normal agent
|
||||
if hasNormalBuiltin {
|
||||
for _, agent := range allAgents {
|
||||
if agent.ID == types.BuiltinAgentNormalID {
|
||||
// Add built-in agents in order
|
||||
for _, builtinID := range builtinIDs {
|
||||
if builtinInDB[builtinID] {
|
||||
// Use customized config from database
|
||||
for _, agent := range allAgents {
|
||||
if agent.ID == builtinID {
|
||||
result = append(result, agent)
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Use default built-in agent
|
||||
if agent := types.GetBuiltinAgent(builtinID, tenantID); agent != nil {
|
||||
result = append(result, agent)
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
result = append(result, types.GetBuiltinNormalAgent(tenantID))
|
||||
}
|
||||
|
||||
// Add built-in agent mode agent
|
||||
if hasAgentBuiltin {
|
||||
for _, agent := range allAgents {
|
||||
if agent.ID == types.BuiltinAgentAgentID {
|
||||
result = append(result, agent)
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
result = append(result, types.GetBuiltinAgentAgent(tenantID))
|
||||
}
|
||||
|
||||
// Add custom agents
|
||||
for _, agent := range allAgents {
|
||||
if agent.ID != types.BuiltinAgentNormalID && agent.ID != types.BuiltinAgentAgentID {
|
||||
if !types.IsBuiltinAgentID(agent.ID) {
|
||||
result = append(result, agent)
|
||||
}
|
||||
}
|
||||
@@ -203,9 +193,8 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo
|
||||
return nil, ErrInvalidTenantID
|
||||
}
|
||||
|
||||
// Handle built-in agents specially
|
||||
isBuiltinAgent := agent.ID == types.BuiltinAgentNormalID || agent.ID == types.BuiltinAgentAgentID
|
||||
if isBuiltinAgent {
|
||||
// Handle built-in agents specially using registry
|
||||
if types.IsBuiltinAgentID(agent.ID) {
|
||||
return s.updateBuiltinAgent(ctx, agent, tenantID)
|
||||
}
|
||||
|
||||
@@ -232,7 +221,6 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo
|
||||
existingAgent.Name = agent.Name
|
||||
existingAgent.Description = agent.Description
|
||||
existingAgent.Avatar = agent.Avatar
|
||||
existingAgent.Type = agent.Type
|
||||
existingAgent.Config = agent.Config
|
||||
existingAgent.UpdatedAt = time.Now()
|
||||
|
||||
@@ -254,12 +242,10 @@ func (s *customAgentService) UpdateAgent(ctx context.Context, agent *types.Custo
|
||||
|
||||
// updateBuiltinAgent updates a built-in agent's configuration (but not basic info)
|
||||
func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *types.CustomAgent, tenantID uint64) (*types.CustomAgent, error) {
|
||||
// Get the default built-in agent
|
||||
var defaultAgent *types.CustomAgent
|
||||
if agent.ID == types.BuiltinAgentNormalID {
|
||||
defaultAgent = types.GetBuiltinNormalAgent(tenantID)
|
||||
} else {
|
||||
defaultAgent = types.GetBuiltinAgentAgent(tenantID)
|
||||
// Get the default built-in agent from registry
|
||||
defaultAgent := types.GetBuiltinAgent(agent.ID, tenantID)
|
||||
if defaultAgent == nil {
|
||||
return nil, ErrAgentNotFound
|
||||
}
|
||||
|
||||
// Try to get existing customized config from database
|
||||
@@ -294,7 +280,6 @@ func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *type
|
||||
Description: defaultAgent.Description,
|
||||
Avatar: defaultAgent.Avatar,
|
||||
IsBuiltin: true,
|
||||
Type: defaultAgent.Type,
|
||||
TenantID: tenantID,
|
||||
Config: agent.Config,
|
||||
CreatedAt: time.Now(),
|
||||
@@ -323,8 +308,8 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {
|
||||
return errors.New("agent ID cannot be empty")
|
||||
}
|
||||
|
||||
// Cannot delete built-in agents
|
||||
if id == types.BuiltinAgentNormalID || id == types.BuiltinAgentAgentID {
|
||||
// Cannot delete built-in agents using registry check
|
||||
if types.IsBuiltinAgentID(id) {
|
||||
return ErrCannotDeleteBuiltin
|
||||
}
|
||||
|
||||
@@ -350,7 +335,7 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {
|
||||
|
||||
logger.Infof(ctx, "Deleting custom agent, ID: %s", id)
|
||||
|
||||
if err := s.repo.DeleteAgent(ctx, id); err != nil {
|
||||
if err := s.repo.DeleteAgent(ctx, id, tenantID); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
})
|
||||
@@ -360,3 +345,52 @@ func (s *customAgentService) DeleteAgent(ctx context.Context, id string) error {
|
||||
logger.Infof(ctx, "Custom agent deleted successfully, ID: %s", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// CopyAgent creates a copy of an existing agent
|
||||
func (s *customAgentService) CopyAgent(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
|
||||
}
|
||||
|
||||
// Get the source agent
|
||||
sourceAgent, err := s.GetAgentByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create a new agent with copied data
|
||||
newAgent := &types.CustomAgent{
|
||||
ID: uuid.New().String(),
|
||||
Name: sourceAgent.Name + " (副本)",
|
||||
Description: sourceAgent.Description,
|
||||
Avatar: sourceAgent.Avatar,
|
||||
IsBuiltin: false, // Copied agents are never built-in
|
||||
TenantID: tenantID,
|
||||
Config: sourceAgent.Config,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Ensure defaults
|
||||
newAgent.EnsureDefaults()
|
||||
|
||||
logger.Infof(ctx, "Copying agent, source ID: %s, new ID: %s", id, newAgent.ID)
|
||||
|
||||
if err := s.repo.CreateAgent(ctx, newAgent); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"source_agent_id": id,
|
||||
"new_agent_id": newAgent.ID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Agent copied successfully, source ID: %s, new ID: %s", id, newAgent.ID)
|
||||
return newAgent, nil
|
||||
}
|
||||
|
||||
@@ -1956,10 +1956,10 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
|
||||
}
|
||||
|
||||
// Replace placeholders
|
||||
prompt = strings.ReplaceAll(prompt, "{{.QuestionCount}}", fmt.Sprintf("%d", questionCount))
|
||||
prompt = strings.ReplaceAll(prompt, "{{.Content}}", content)
|
||||
prompt = strings.ReplaceAll(prompt, "{{.Context}}", contextSection)
|
||||
prompt = strings.ReplaceAll(prompt, "{{.DocName}}", docName)
|
||||
prompt = strings.ReplaceAll(prompt, "{{question_count}}", fmt.Sprintf("%d", questionCount))
|
||||
prompt = strings.ReplaceAll(prompt, "{{content}}", content)
|
||||
prompt = strings.ReplaceAll(prompt, "{{context}}", contextSection)
|
||||
prompt = strings.ReplaceAll(prompt, "{{doc_name}}", docName)
|
||||
|
||||
thinking := false
|
||||
response, err := chatModel.Chat(ctx, []chat.Message{
|
||||
@@ -2000,11 +2000,11 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
|
||||
// Default prompt for question generation with context support
|
||||
const defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。
|
||||
|
||||
{{.Context}}
|
||||
{{context}}
|
||||
## 主要内容(请基于此内容生成问题)
|
||||
文档名称:{{.DocName}}
|
||||
文档名称:{{doc_name}}
|
||||
文档内容:
|
||||
{{.Content}}
|
||||
{{content}}
|
||||
|
||||
## 核心要求
|
||||
- 生成的问题必须与【主要内容】直接相关
|
||||
@@ -2013,7 +2013,7 @@ const defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手
|
||||
- 问题应该是用户在实际场景中可能会提出的自然问题
|
||||
- 问题应该多样化,覆盖内容的不同方面
|
||||
- 每个问题应该简洁明了,长度控制在30字以内
|
||||
- 生成的问题数量为 {{.QuestionCount}} 个
|
||||
- 生成的问题数量为 {{question_count}} 个
|
||||
|
||||
## 问题类型建议
|
||||
- 定义类:什么是...?...是什么?
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent"
|
||||
"github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
@@ -271,7 +269,7 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
|
||||
if model == nil {
|
||||
continue
|
||||
}
|
||||
if model.Type == types.ModelTypeKnowledgeQA {
|
||||
if model.Type == types.ModelTypeKnowledgeQA {
|
||||
modelID = model.ID
|
||||
logger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID)
|
||||
break
|
||||
@@ -469,6 +467,11 @@ func (s *sessionService) KnowledgeQA(
|
||||
// Ensure defaults are set
|
||||
customAgent.EnsureDefaults()
|
||||
|
||||
// Override model ID
|
||||
if customAgent.Config.ModelID != "" {
|
||||
chatModelID = customAgent.Config.ModelID
|
||||
logger.Infof(ctx, "Using custom agent's model_id: %s", chatModelID)
|
||||
}
|
||||
// Override system prompt
|
||||
if customAgent.Config.SystemPrompt != "" {
|
||||
summaryConfig.Prompt = customAgent.Config.SystemPrompt
|
||||
@@ -588,10 +591,18 @@ func (s *sessionService) KnowledgeQA(
|
||||
// Otherwise use rag_stream pipeline (which handles both KB search and web search)
|
||||
var pipeline []types.EventType
|
||||
if len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 && !webSearchEnabled {
|
||||
logger.Info(ctx, "No knowledge bases selected and web search disabled, using chat_stream pipeline")
|
||||
pipeline = types.Pipline["chat_stream"]
|
||||
logger.Info(ctx, "No knowledge bases selected and web search disabled, using chat pipeline")
|
||||
// For pure chat, UserContent is the Query (since INTO_CHAT_MESSAGE is skipped)
|
||||
chatManage.UserContent = query
|
||||
|
||||
// Use chat_history_stream if multi-turn is enabled, otherwise use chat_stream
|
||||
if maxRounds > 0 {
|
||||
logger.Infof(ctx, "Multi-turn enabled with maxRounds=%d, using chat_history_stream pipeline", maxRounds)
|
||||
pipeline = types.Pipline["chat_history_stream"]
|
||||
} else {
|
||||
logger.Info(ctx, "Multi-turn disabled, using chat_stream pipeline")
|
||||
pipeline = types.Pipline["chat_stream"]
|
||||
}
|
||||
} else {
|
||||
if webSearchEnabled && len(knowledgeBaseIDs) == 0 && len(knowledgeIDs) == 0 {
|
||||
logger.Info(ctx, "Web search enabled without knowledge bases, using rag_stream pipeline for web search only")
|
||||
@@ -1057,6 +1068,8 @@ func (s *sessionService) AgentQA(
|
||||
MultiTurnEnabled: customAgent.Config.MultiTurnEnabled,
|
||||
HistoryTurns: customAgent.Config.HistoryTurns,
|
||||
KnowledgeBases: customAgent.Config.KnowledgeBases,
|
||||
MCPSelectionMode: customAgent.Config.MCPSelectionMode,
|
||||
MCPServices: customAgent.Config.MCPServices,
|
||||
}
|
||||
|
||||
// Use custom agent's allowed tools if specified, otherwise use defaults
|
||||
@@ -1442,20 +1455,9 @@ func (s *sessionService) handleModelFallback(ctx context.Context, chatManage *ty
|
||||
|
||||
// renderFallbackPrompt renders the fallback prompt template with Query variable
|
||||
func (s *sessionService) renderFallbackPrompt(ctx context.Context, chatManage *types.ChatManage) (string, error) {
|
||||
tmpl, err := template.New("fallbackPrompt").Parse(chatManage.FallbackPrompt)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse template: %w", err)
|
||||
}
|
||||
|
||||
var promptContent bytes.Buffer
|
||||
err = tmpl.Execute(&promptContent, map[string]interface{}{
|
||||
"Query": chatManage.Query,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to execute template: %w", err)
|
||||
}
|
||||
|
||||
return promptContent.String(), nil
|
||||
// Use simple string replacement instead of Go template
|
||||
result := strings.ReplaceAll(chatManage.FallbackPrompt, "{{query}}", chatManage.Query)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// consumeFallbackStream consumes the streaming response and emits events
|
||||
|
||||
Reference in New Issue
Block a user