refactor: 调整智能体配置,增强智能体选择与状态管理

This commit is contained in:
wizardchen
2025-12-26 21:31:02 +08:00
parent abfe87eaed
commit 0ca947981a
36 changed files with 2421 additions and 916 deletions
+14 -16
View File
@@ -4,6 +4,8 @@ import (
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/types"
)
// formatFileSize formats file size in human-readable format
@@ -78,6 +80,7 @@ type KnowledgeBaseInfo struct {
}
// PlaceholderDefinition defines a placeholder exposed to UI/configuration
// Deprecated: Use types.PromptPlaceholder instead
type PlaceholderDefinition struct {
Name string `json:"name"`
Label string `json:"label"`
@@ -85,24 +88,19 @@ type PlaceholderDefinition struct {
}
// AvailablePlaceholders lists all supported prompt placeholders for UI hints
// This returns agent mode specific placeholders
func AvailablePlaceholders() []PlaceholderDefinition {
return []PlaceholderDefinition{
{
Name: "knowledge_bases",
Label: "知识库列表",
Description: "自动格式化为表格形式的知识库列表,包含知识库名称、描述、文档数量、最近添加的文档等信息",
},
{
Name: "web_search_status",
Label: "网络检索模式开关状态",
Description: "网络检索(web_search)工具是否启用的状态说明,值为 Enabled 或 Disabled",
},
{
Name: "current_time",
Label: "当前系统时间",
Description: "格式为 RFC3339 的当前系统时间,用于帮助模型感知实时性",
},
// Use centralized placeholder definitions from types package
placeholders := types.PlaceholdersByField(types.PromptFieldAgentSystemPrompt)
result := make([]PlaceholderDefinition, len(placeholders))
for i, p := range placeholders {
result[i] = PlaceholderDefinition{
Name: p.Name,
Label: p.Label,
Description: p.Description,
}
}
return result
}
// formatKnowledgeBaseList formats knowledge base information for the prompt
@@ -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
}
+41 -15
View File
@@ -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()
}
+88 -54
View File
@@ -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
}
+8 -8
View File
@@ -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}} 个
## 问题类型建议
- 定义类:什么是...?...是什么?
+21 -19
View File
@@ -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
+1
View File
@@ -145,6 +145,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Invoke(chatpipline.NewPluginStreamFilter))
must(container.Invoke(chatpipline.NewPluginFilterTopK))
must(container.Invoke(chatpipline.NewPluginRewrite))
must(container.Invoke(chatpipline.NewPluginLoadHistory))
must(container.Invoke(chatpipline.NewPluginExtractEntity))
must(container.Invoke(chatpipline.NewPluginSearchEntity))
must(container.Invoke(chatpipline.NewPluginSearchParallel))
+79 -6
View File
@@ -29,7 +29,6 @@ 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"`
}
@@ -38,7 +37,6 @@ type UpdateAgentRequest struct {
Name string `json:"name"`
Description string `json:"description"`
Avatar string `json:"avatar"`
Type types.CustomAgentType `json:"type"`
Config types.CustomAgentConfig `json:"config"`
}
@@ -72,12 +70,11 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
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)
logger.Infof(ctx, "Creating custom agent, name: %s, agent_mode: %s",
secutils.SanitizeForLog(req.Name), req.Config.AgentMode)
// Create agent using the service
createdAgent, err := h.service.CreateAgent(ctx, agent)
@@ -211,7 +208,6 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
Name: req.Name,
Description: req.Description,
Avatar: req.Avatar,
Type: req.Type,
Config: req.Config,
}
@@ -296,3 +292,80 @@ func (h *CustomAgentHandler) DeleteAgent(c *gin.Context) {
"message": "Agent deleted successfully",
})
}
// CopyAgent godoc
// @Summary 复制智能体
// @Description 复制指定的智能体
// @Tags 智能体
// @Accept json
// @Produce json
// @Param id path string true "智能体ID"
// @Success 201 {object} map[string]interface{} "复制成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "智能体不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents/{id}/copy [post]
func (h *CustomAgentHandler) CopyAgent(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start copying 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, "Copying custom agent, ID: %s", secutils.SanitizeForLog(id))
// Copy the agent
copiedAgent, err := h.service.CopyAgent(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"))
default:
c.Error(errors.NewInternalServerError(err.Error()))
}
return
}
logger.Infof(ctx, "Custom agent copied successfully, source ID: %s, new ID: %s",
secutils.SanitizeForLog(id), secutils.SanitizeForLog(copiedAgent.ID))
c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": copiedAgent,
})
}
// GetPlaceholders godoc
// @Summary 获取占位符定义
// @Description 获取所有可用的提示词占位符定义,按字段类型分组
// @Tags 智能体
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "占位符定义"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /agents/placeholders [get]
func (h *CustomAgentHandler) GetPlaceholders(c *gin.Context) {
// Return all placeholder definitions grouped by field type
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"all": types.AllPlaceholders(),
"system_prompt": types.PlaceholdersByField(types.PromptFieldSystemPrompt),
"agent_system_prompt": types.PlaceholdersByField(types.PromptFieldAgentSystemPrompt),
"context_template": types.PlaceholdersByField(types.PromptFieldContextTemplate),
"rewrite_system_prompt": types.PlaceholdersByField(types.PromptFieldRewriteSystemPrompt),
"rewrite_prompt": types.PlaceholdersByField(types.PromptFieldRewritePrompt),
"fallback_prompt": types.PlaceholdersByField(types.PromptFieldFallbackPrompt),
},
})
}
+2 -2
View File
@@ -81,8 +81,8 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
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)
logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s",
customAgent.ID, customAgent.Name, customAgent.IsBuiltin, customAgent.Config.AgentMode)
}
}
+4
View File
@@ -417,6 +417,8 @@ func RegisterWebSearchRoutes(r *gin.RouterGroup, webSearchHandler *handler.WebSe
func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAgentHandler) {
agents := r.Group("/agents")
{
// Get placeholder definitions (must be before /:id to avoid conflict)
agents.GET("/placeholders", agentHandler.GetPlaceholders)
// Create custom agent
agents.POST("", agentHandler.CreateAgent)
// List all agents (including built-in)
@@ -427,5 +429,7 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomA
agents.PUT("/:id", agentHandler.UpdateAgent)
// Delete agent
agents.DELETE("/:id", agentHandler.DeleteAgent)
// Copy agent
agents.POST("/:id/copy", agentHandler.CopyAgent)
}
}
+3
View File
@@ -24,6 +24,9 @@ type AgentConfig struct {
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)
// MCP service selection
MCPSelectionMode string `json:"mcp_selection_mode"` // MCP selection mode: "all", "selected", "none"
MCPServices []string `json:"mcp_services"` // Selected MCP service IDs (when mode is "selected")
}
// SessionAgentConfig represents session-level agent configuration
+7 -1
View File
@@ -124,6 +124,7 @@ func (c *ChatManage) Clone() *ChatManage {
type EventType string
const (
LOAD_HISTORY EventType = "load_history" // Load conversation history without rewriting
REWRITE_QUERY EventType = "rewrite_query" // Query rewriting for better retrieval
CHUNK_SEARCH EventType = "chunk_search" // Search for relevant chunks
CHUNK_SEARCH_PARALLEL EventType = "chunk_search_parallel" // Parallel search: chunks + entities
@@ -142,7 +143,12 @@ var Pipline = map[string][]EventType{
"chat": { // Simple chat without retrieval
CHAT_COMPLETION,
},
"chat_stream": { // Streaming chat without retrieval
"chat_stream": { // Streaming chat without retrieval (no history)
CHAT_COMPLETION_STREAM,
STREAM_FILTER,
},
"chat_history_stream": { // Streaming chat with conversation history
LOAD_HISTORY,
CHAT_COMPLETION_STREAM,
STREAM_FILTER,
},
+91 -65
View File
@@ -8,27 +8,27 @@ import (
"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"
// BuiltinQuickAnswerID is the ID for the built-in quick answer (RAG) agent
BuiltinQuickAnswerID = "builtin-quick-answer"
// BuiltinSmartReasoningID is the ID for the built-in smart reasoning (ReAct) agent
BuiltinSmartReasoningID = "builtin-smart-reasoning"
)
// AgentMode constants for agent running mode
const (
// AgentModeQuickAnswer is the RAG mode for quick Q&A
AgentModeQuickAnswer = "quick-answer"
// AgentModeSmartReasoning is the ReAct mode for multi-step reasoning
AgentModeSmartReasoning = "smart-reasoning"
)
// CustomAgent represents a configurable AI agent (similar to GPTs)
type CustomAgent struct {
// Unique identifier of the agent
// Unique identifier of the agent (composite primary key with TenantID)
// For built-in agents, this is 'builtin-quick-answer' or 'builtin-smart-reasoning'
// For custom agents, this is a UUID
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"`
@@ -38,10 +38,8 @@ type CustomAgent struct {
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"`
// Tenant ID (composite primary key with ID)
TenantID uint64 `yaml:"tenant_id" json:"tenant_id" gorm:"primaryKey"`
// Created by user ID
CreatedBy string `yaml:"created_by" json:"created_by" gorm:"type:varchar(36)"`
@@ -57,7 +55,7 @@ type CustomAgent struct {
// CustomAgentConfig represents the configuration of a custom agent
type CustomAgentConfig struct {
// ===== Basic Settings =====
// Agent mode: "normal" for RAG mode, "agent" for ReAct agent mode
// Agent mode: "quick-answer" for RAG mode, "smart-reasoning" for ReAct agent mode
AgentMode string `yaml:"agent_mode" json:"agent_mode"`
// System prompt for the agent (for normal mode, or agent mode when web search is disabled)
SystemPrompt string `yaml:"system_prompt" json:"system_prompt"`
@@ -83,16 +81,16 @@ type CustomAgentConfig struct {
AllowedTools []string `yaml:"allowed_tools" json:"allowed_tools"`
// Whether reflection is enabled (only for agent type)
ReflectionEnabled bool `yaml:"reflection_enabled" json:"reflection_enabled"`
// MCP service selection mode: "all" = all enabled MCP services, "selected" = specific services, "none" = no MCP
MCPSelectionMode string `yaml:"mcp_selection_mode" json:"mcp_selection_mode"`
// Selected MCP service IDs (only used when MCPSelectionMode is "selected")
MCPServices []string `yaml:"mcp_services" json:"mcp_services"`
// ===== Knowledge Base Settings =====
// Knowledge base selection mode: "all" = all KBs, "selected" = specific KBs, "none" = no KB
KBSelectionMode string `yaml:"kb_selection_mode" json:"kb_selection_mode"`
// Associated knowledge base IDs (only used when KBSelectionMode is "selected")
KnowledgeBases []string `yaml:"knowledge_bases" json:"knowledge_bases"`
// Whether to allow user to select knowledge bases during conversation
// If true, user can select from available KBs (all or selected based on KBSelectionMode)
// If false, the configured KBs are used automatically without user selection
AllowUserKBSelection *bool `yaml:"allow_user_kb_selection" json:"allow_user_kb_selection"`
// ===== Web Search Settings =====
// Whether web search is enabled
@@ -162,9 +160,6 @@ func (a *CustomAgent) EnsureDefaults() {
if a == nil {
return
}
if a.Type == "" {
a.Type = CustomAgentTypeCustom
}
if a.Config.Temperature == 0 {
a.Config.Temperature = 0.7
}
@@ -204,33 +199,33 @@ func (a *CustomAgent) EnsureDefaults() {
// IsAgentMode returns true if this agent uses ReAct agent mode
func (a *CustomAgent) IsAgentMode() bool {
return a.Config.AgentMode == "agent"
return a.Config.AgentMode == AgentModeSmartReasoning
}
// GetBuiltinNormalAgent returns the built-in normal mode agent
func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {
// GetBuiltinQuickAnswerAgent returns the built-in quick answer (RAG) mode agent
func GetBuiltinQuickAnswerAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinAgentNormalID,
Name: "普通模式",
ID: BuiltinQuickAnswerID,
Name: "快速问答",
Description: "基于知识库的 RAG 问答,快速准确地回答问题",
Avatar: "💬",
IsBuiltin: true,
Type: CustomAgentTypeNormal,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: "normal",
SystemPrompt: "",
Temperature: 0.7,
MaxCompletionTokens: 2048,
WebSearchEnabled: false,
MultiTurnEnabled: true,
HistoryTurns: 5,
AgentMode: AgentModeQuickAnswer,
SystemPrompt: "",
Temperature: 0.7,
MaxCompletionTokens: 2048,
WebSearchEnabled: true,
WebSearchMaxResults: 5,
MultiTurnEnabled: true,
HistoryTurns: 5,
KBSelectionMode: "all",
// Retrieval strategy
EmbeddingTopK: 10,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 5,
RerankThreshold: 0.5,
EmbeddingTopK: 10,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 10,
RerankThreshold: 0.3,
// Advanced settings
EnableQueryExpansion: true,
EnableRewrite: true,
@@ -239,21 +234,21 @@ func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {
}
}
// GetBuiltinAgentAgent returns the built-in agent mode agent
func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
// GetBuiltinSmartReasoningAgent returns the built-in smart reasoning (ReAct) mode agent
func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinAgentAgentID,
Name: "Agent 模式",
ID: BuiltinSmartReasoningID,
Name: "智能推理",
Description: "ReAct 推理框架,支持多步思考和工具调用",
Avatar: "🤖",
IsBuiltin: true,
Type: CustomAgentTypeAgent,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: "agent",
AgentMode: AgentModeSmartReasoning,
SystemPrompt: "",
Temperature: 0.7,
MaxIterations: 10,
MaxCompletionTokens: 2048,
MaxIterations: 50,
KBSelectionMode: "all",
AllowedTools: []string{"thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"},
WebSearchEnabled: true,
WebSearchMaxResults: 5,
@@ -261,19 +256,50 @@ func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
MultiTurnEnabled: true,
HistoryTurns: 5,
// Retrieval strategy
EmbeddingTopK: 10,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 5,
RerankThreshold: 0.5,
EmbeddingTopK: 10,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 10,
RerankThreshold: 0.3,
},
}
}
// GetBuiltinAgents returns all built-in agents for a tenant
func GetBuiltinAgents(tenantID uint64) []*CustomAgent {
return []*CustomAgent{
GetBuiltinNormalAgent(tenantID),
GetBuiltinAgentAgent(tenantID),
}
// Deprecated: Use GetBuiltinQuickAnswerAgent instead
func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {
return GetBuiltinQuickAnswerAgent(tenantID)
}
// Deprecated: Use GetBuiltinSmartReasoningAgent instead
func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
return GetBuiltinSmartReasoningAgent(tenantID)
}
// BuiltinAgentRegistry provides a registry of all built-in agents for easy extension
var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{
BuiltinQuickAnswerID: GetBuiltinQuickAnswerAgent,
BuiltinSmartReasoningID: GetBuiltinSmartReasoningAgent,
}
// GetBuiltinAgentIDs returns all built-in agent IDs
func GetBuiltinAgentIDs() []string {
ids := make([]string, 0, len(BuiltinAgentRegistry))
for id := range BuiltinAgentRegistry {
ids = append(ids, id)
}
return ids
}
// IsBuiltinAgentID checks if the given ID is a built-in agent ID
func IsBuiltinAgentID(id string) bool {
_, exists := BuiltinAgentRegistry[id]
return exists
}
// GetBuiltinAgent returns a built-in agent by ID, or nil if not found
func GetBuiltinAgent(id string, tenantID uint64) *CustomAgent {
if factory, exists := BuiltinAgentRegistry[id]; exists {
return factory(tenantID)
}
return nil
}
+11 -1
View File
@@ -52,6 +52,15 @@ type CustomAgentService interface {
// Returns:
// - Possible errors such as not existing, insufficient permissions, cannot delete built-in, etc.
DeleteAgent(ctx context.Context, id string) error
// CopyAgent creates a copy of an existing agent
// Parameters:
// - ctx: Context information
// - id: Unique identifier of the agent to copy
// Returns:
// - The newly created agent copy
// - Possible errors such as not existing, insufficient permissions, etc.
CopyAgent(ctx context.Context, id string) (*types.CustomAgent, error)
}
// CustomAgentRepository defines the custom agent repository interface
@@ -96,7 +105,8 @@ type CustomAgentRepository interface {
// Parameters:
// - ctx: Context information
// - id: Agent ID
// - tenantID: Tenant ID for isolation (required for composite primary key)
// Returns:
// - Possible errors such as record not existing, database errors, etc.
DeleteAgent(ctx context.Context, id string) error
DeleteAgent(ctx context.Context, id string, tenantID uint64) error
}
+165
View File
@@ -0,0 +1,165 @@
package types
// PromptPlaceholder represents a placeholder that can be used in prompt templates
type PromptPlaceholder struct {
// Name is the placeholder name (without braces), e.g., "query"
Name string `json:"name"`
// Label is a short label for the placeholder
Label string `json:"label"`
// Description explains what this placeholder represents
Description string `json:"description"`
}
// PromptFieldType represents the type of prompt field
type PromptFieldType string
const (
// PromptFieldSystemPrompt is for system prompts (normal mode)
PromptFieldSystemPrompt PromptFieldType = "system_prompt"
// PromptFieldAgentSystemPrompt is for agent mode system prompts
PromptFieldAgentSystemPrompt PromptFieldType = "agent_system_prompt"
// PromptFieldContextTemplate is for context templates
PromptFieldContextTemplate PromptFieldType = "context_template"
// PromptFieldRewriteSystemPrompt is for rewrite system prompts
PromptFieldRewriteSystemPrompt PromptFieldType = "rewrite_system_prompt"
// PromptFieldRewritePrompt is for rewrite user prompts
PromptFieldRewritePrompt PromptFieldType = "rewrite_prompt"
// PromptFieldFallbackPrompt is for fallback prompts
PromptFieldFallbackPrompt PromptFieldType = "fallback_prompt"
)
// All available placeholders in the system
var (
// Common placeholders
PlaceholderQuery = PromptPlaceholder{
Name: "query",
Label: "用户问题",
Description: "用户当前的问题或查询内容",
}
PlaceholderContexts = PromptPlaceholder{
Name: "contexts",
Label: "检索内容",
Description: "从知识库检索到的相关内容列表",
}
PlaceholderCurrentTime = PromptPlaceholder{
Name: "current_time",
Label: "当前时间",
Description: "当前系统时间(格式:2006-01-02 15:04:05)",
}
PlaceholderCurrentWeek = PromptPlaceholder{
Name: "current_week",
Label: "当前星期",
Description: "当前星期几(如:星期一、Monday)",
}
// Rewrite prompt placeholders
PlaceholderConversation = PromptPlaceholder{
Name: "conversation",
Label: "历史对话",
Description: "格式化的历史对话内容,用于多轮对话改写",
}
PlaceholderYesterday = PromptPlaceholder{
Name: "yesterday",
Label: "昨天日期",
Description: "昨天的日期(格式:2006-01-02)",
}
PlaceholderAnswer = PromptPlaceholder{
Name: "answer",
Label: "助手回答",
Description: "助手的回答内容(用于对话历史格式化)",
}
// Agent mode specific placeholders
PlaceholderKnowledgeBases = PromptPlaceholder{
Name: "knowledge_bases",
Label: "知识库列表",
Description: "自动格式化的知识库列表,包含名称、描述、文档数量等信息",
}
PlaceholderWebSearchStatus = PromptPlaceholder{
Name: "web_search_status",
Label: "网络搜索状态",
Description: "网络搜索工具是否启用的状态(Enabled 或 Disabled)",
}
)
// PlaceholdersByField returns the available placeholders for a specific prompt field type
func PlaceholdersByField(fieldType PromptFieldType) []PromptPlaceholder {
switch fieldType {
case PromptFieldSystemPrompt:
// Normal mode system prompt
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderContexts,
PlaceholderCurrentTime,
PlaceholderCurrentWeek,
}
case PromptFieldAgentSystemPrompt:
// Agent mode system prompt
return []PromptPlaceholder{
PlaceholderKnowledgeBases,
PlaceholderWebSearchStatus,
PlaceholderCurrentTime,
}
case PromptFieldContextTemplate:
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderContexts,
PlaceholderCurrentTime,
PlaceholderCurrentWeek,
}
case PromptFieldRewriteSystemPrompt:
// Rewrite system prompt supports same placeholders as rewrite user prompt
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderConversation,
PlaceholderCurrentTime,
PlaceholderYesterday,
}
case PromptFieldRewritePrompt:
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderConversation,
PlaceholderCurrentTime,
PlaceholderYesterday,
}
case PromptFieldFallbackPrompt:
return []PromptPlaceholder{
PlaceholderQuery,
}
default:
return []PromptPlaceholder{}
}
}
// AllPlaceholders returns all available placeholders in the system
func AllPlaceholders() []PromptPlaceholder {
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderContexts,
PlaceholderCurrentTime,
PlaceholderCurrentWeek,
PlaceholderConversation,
PlaceholderYesterday,
PlaceholderAnswer,
PlaceholderKnowledgeBases,
PlaceholderWebSearchStatus,
}
}
// PlaceholderMap returns a map of field types to their available placeholders
func PlaceholderMap() map[PromptFieldType][]PromptPlaceholder {
return map[PromptFieldType][]PromptPlaceholder{
PromptFieldSystemPrompt: PlaceholdersByField(PromptFieldSystemPrompt),
PromptFieldAgentSystemPrompt: PlaceholdersByField(PromptFieldAgentSystemPrompt),
PromptFieldContextTemplate: PlaceholdersByField(PromptFieldContextTemplate),
PromptFieldRewriteSystemPrompt: PlaceholdersByField(PromptFieldRewriteSystemPrompt),
PromptFieldRewritePrompt: PlaceholdersByField(PromptFieldRewritePrompt),
PromptFieldFallbackPrompt: PlaceholdersByField(PromptFieldFallbackPrompt),
}
}
+4 -2
View File
@@ -69,13 +69,15 @@ type Tenant struct {
StorageQuota int64 `yaml:"storage_quota" json:"storage_quota" gorm:"default:10737418240"`
// Storage used (Bytes)
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
// Global Agent configuration for this tenant (default for all sessions)
// Deprecated: AgentConfig is deprecated, use CustomAgent (builtin-smart-reasoning) config instead.
// This field is kept for backward compatibility and will be removed in future versions.
AgentConfig *AgentConfig `yaml:"agent_config" json:"agent_config" gorm:"type:jsonb"`
// Global Context configuration for this tenant (default for all sessions)
ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:jsonb"`
// Global WebSearch configuration for this tenant
WebSearchConfig *WebSearchConfig `yaml:"web_search_config" json:"web_search_config" gorm:"type:jsonb"`
// Global Conversation configuration for this tenant (default for normal mode sessions)
// Deprecated: ConversationConfig is deprecated, use CustomAgent (builtin-quick-answer) config instead.
// This field is kept for backward compatibility and will be removed in future versions.
ConversationConfig *ConversationConfig `yaml:"conversation_config" json:"conversation_config" gorm:"type:jsonb"`
// Creation time
CreatedAt time.Time `yaml:"created_at" json:"created_at"`