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
+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"`