feat: Enhance chat and knowledge base functionalities with multi-KB support

- Updated agentChat API to accept optional knowledge_base_ids and agent_enabled parameters.
- Introduced getSession API to retrieve session details.
- Modified useStream to validate knowledge_base_ids for agent-chat requests and prepare POST body accordingly.
- Enhanced createKnowledgeBase API to include additional configuration options.
- Refactored chat routing to remove knowledge base ID from the chat path, allowing for dynamic knowledge base selection.
- Improved session management by preventing duplicate session entries in the menu store.
- Updated UI components for better session handling and display.
- Added context management for agent conversations to improve state persistence across sessions.
This commit is contained in:
wizardchen
2025-11-06 21:12:26 +08:00
parent 602e8a3b88
commit 266b9a5943
41 changed files with 3188 additions and 1746 deletions
+26 -1
View File
@@ -7,7 +7,8 @@ import (
"time"
)
// AgentConfig represents the configuration for an agent session
// AgentConfig represents the full agent configuration (used at tenant level and runtime)
// This includes all configuration parameters for agent execution
type AgentConfig struct {
Enabled bool `json:"enabled"` // Whether agent mode is enabled
MaxIterations int `json:"max_iterations"` // Maximum number of ReAct iterations
@@ -19,6 +20,13 @@ type AgentConfig struct {
KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs
}
// SessionAgentConfig represents session-level agent configuration
// Sessions only store Enabled and KnowledgeBases; other configs are read from Tenant at runtime
type SessionAgentConfig struct {
Enabled bool `json:"enabled"` // Whether agent mode is enabled for this session
KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs for this session
}
// Value implements driver.Valuer interface for AgentConfig
func (c AgentConfig) Value() (driver.Value, error) {
return json.Marshal(c)
@@ -36,6 +44,23 @@ func (c *AgentConfig) Scan(value interface{}) error {
return json.Unmarshal(b, c)
}
// Value implements driver.Valuer interface for SessionAgentConfig
func (c SessionAgentConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements sql.Scanner interface for SessionAgentConfig
func (c *SessionAgentConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
// Tool defines the interface that all agent tools must implement
type Tool interface {
// Name returns the unique identifier for this tool
+4
View File
@@ -54,6 +54,10 @@ const (
ResponseTypeError ResponseType = "error"
// Reflection response type (for agent reflection)
ResponseTypeReflection ResponseType = "reflection"
// Session title response type
ResponseTypeSessionTitle ResponseType = "session_title"
// Agent query response type (query received and processing started)
ResponseTypeAgentQuery ResponseType = "agent_query"
)
// StreamResponse stream response
+11 -5
View File
@@ -9,11 +9,12 @@ type ChatManage struct {
RewriteQuery string `json:"rewrite_query,omitempty"` // Query after rewriting for better retrieval
History []*History `json:"history,omitempty"` // Chat history for context
KnowledgeBaseID string `json:"knowledge_base_id"` // ID of the knowledge base to search against
VectorThreshold float64 `json:"vector_threshold"` // Minimum score threshold for vector search results
KeywordThreshold float64 `json:"keyword_threshold"` // Minimum score threshold for keyword search results
EmbeddingTopK int `json:"embedding_top_k"` // Number of top results to retrieve from embedding search
VectorDatabase string `json:"vector_database"` // Vector database type/name to use
KnowledgeBaseID string `json:"knowledge_base_id"` // ID of the knowledge base to search against (deprecated, use KnowledgeBaseIDs)
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // IDs of knowledge bases to search (multi-KB support)
VectorThreshold float64 `json:"vector_threshold"` // Minimum score threshold for vector search results
KeywordThreshold float64 `json:"keyword_threshold"` // Minimum score threshold for keyword search results
EmbeddingTopK int `json:"embedding_top_k"` // Number of top results to retrieve from embedding search
VectorDatabase string `json:"vector_database"` // Vector database type/name to use
RerankModelID string `json:"rerank_model_id"` // Model ID for reranking search results
RerankTopK int `json:"rerank_top_k"` // Number of top results after reranking
@@ -37,12 +38,17 @@ type ChatManage struct {
// Clone creates a deep copy of the ChatManage object
func (c *ChatManage) Clone() *ChatManage {
// Deep copy knowledge base IDs slice
knowledgeBaseIDs := make([]string, len(c.KnowledgeBaseIDs))
copy(knowledgeBaseIDs, c.KnowledgeBaseIDs)
return &ChatManage{
Query: c.Query,
ProcessedQuery: c.ProcessedQuery,
RewriteQuery: c.RewriteQuery,
SessionID: c.SessionID,
KnowledgeBaseID: c.KnowledgeBaseID,
KnowledgeBaseIDs: knowledgeBaseIDs,
VectorThreshold: c.VectorThreshold,
KeywordThreshold: c.KeywordThreshold,
EmbeddingTopK: c.EmbeddingTopK,
+3 -3
View File
@@ -20,13 +20,13 @@ type AgentStreamEvent struct {
// AgentEngine defines the interface for agent execution engine
type AgentEngine interface {
// ExecuteStreamWithHistory executes the agent with conversation history and returns a stream of events
Execute(ctx context.Context, sessionID, query string, llmContext []chat.Message) (*types.AgentState, error)
Execute(ctx context.Context, sessionID, messageID, query string, llmContext []chat.Message) (*types.AgentState, error)
}
// AgentService defines the interface for agent-related operations
type AgentService interface {
// CreateAgentEngine creates an agent engine with the given configuration and EventBus
CreateAgentEngine(ctx context.Context, config *types.AgentConfig, eventBus *event.EventBus) (AgentEngine, error)
// CreateAgentEngine creates an agent engine with the given configuration, EventBus, and ContextManager
CreateAgentEngine(ctx context.Context, config *types.AgentConfig, eventBus *event.EventBus, contextManager ContextManager, sessionID string) (AgentEngine, error)
// ValidateConfig validates an agent configuration
ValidateConfig(config *types.AgentConfig) error
+8 -2
View File
@@ -22,10 +22,14 @@ type SessionService interface {
// DeleteSession deletes a session
DeleteSession(ctx context.Context, id string) error
// GenerateTitle generates a title for the current conversation
GenerateTitle(ctx context.Context, sessionID string, messages []types.Message) (string, error)
GenerateTitle(ctx context.Context, session *types.Session, messages []types.Message) (string, error)
// GenerateTitleAsync generates a title for the session asynchronously
// It emits an event when the title is generated
GenerateTitleAsync(ctx context.Context, session *types.Session, userQuery string, eventBus *event.EventBus)
// KnowledgeQA performs knowledge-based question answering
// knowledgeBaseIDs: list of knowledge base IDs to search (supports multi-KB)
KnowledgeQA(ctx context.Context,
sessionID, query string,
session *types.Session, query string, knowledgeBaseIDs []string,
) ([]*types.SearchResult, <-chan types.StreamResponse, error)
// KnowledgeQAByEvent performs knowledge-based question answering by event
KnowledgeQAByEvent(ctx context.Context, chatManage *types.ChatManage, eventList []types.EventType) error
@@ -34,6 +38,8 @@ type SessionService interface {
// AgentQA performs agent-based question answering with conversation history and streaming support
// eventBus is optional - if nil, uses service's default EventBus
AgentQA(ctx context.Context, session *types.Session, query string, assistantMessageID string, eventBus *event.EventBus) ([]*types.SearchResult, error)
// ClearContext clears the LLM context for a session
ClearContext(ctx context.Context, sessionID string) error
}
// SessionRepository defines the session repository interface
+17 -17
View File
@@ -64,8 +64,8 @@ type ContextConfig struct {
// For sliding_window: number of messages to keep
// For smart: number of recent messages to keep uncompressed
RecentMessageCount int `json:"recent_message_count"`
// Enable context management (default: true)
Enabled bool `json:"enabled"`
// Summarize threshold: number of messages before summarization
SummarizeThreshold int `json:"summarize_threshold"`
}
// Session represents the session
@@ -80,21 +80,21 @@ type Session struct {
TenantID uint `json:"tenant_id" gorm:"index"`
// Strategy configuration
KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID
MaxRounds int `json:"max_rounds"` // 多轮保持轮数
EnableRewrite bool `json:"enable_rewrite"` // 多轮改写开关
FallbackStrategy FallbackStrategy `json:"fallback_strategy"` // 兜底策略
FallbackResponse string `json:"fallback_response"` // 固定回复内容
EmbeddingTopK int `json:"embedding_top_k"` // 向量召回TopK
KeywordThreshold float64 `json:"keyword_threshold"` // 关键词召回阈值
VectorThreshold float64 `json:"vector_threshold"` // 向量召回阈值
RerankModelID string `json:"rerank_model_id"` // 排序模型ID
RerankTopK int `json:"rerank_top_k"` // 排序TopK
RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值
SummaryModelID string `json:"summary_model_id"` // 总结模型ID
SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数
AgentConfig *AgentConfig `json:"agent_config" gorm:"type:json"` // Agent 配置(可选)
ContextConfig *ContextConfig `json:"context_config" gorm:"type:json"` // 上下文管理配置(可选)
KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID
MaxRounds int `json:"max_rounds"` // 多轮保持轮数
EnableRewrite bool `json:"enable_rewrite"` // 多轮改写开关
FallbackStrategy FallbackStrategy `json:"fallback_strategy"` // 兜底策略
FallbackResponse string `json:"fallback_response"` // 固定回复内容
EmbeddingTopK int `json:"embedding_top_k"` // 向量召回TopK
KeywordThreshold float64 `json:"keyword_threshold"` // 关键词召回阈值
VectorThreshold float64 `json:"vector_threshold"` // 向量召回阈值
RerankModelID string `json:"rerank_model_id"` // 排序模型ID
RerankTopK int `json:"rerank_top_k"` // 排序TopK
RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值
SummaryModelID string `json:"summary_model_id"` // 总结模型ID
SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数
AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:json"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases)
ContextConfig *ContextConfig `json:"context_config" gorm:"type:json"` // 上下文管理配置(可选)
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
+2
View File
@@ -30,6 +30,8 @@ type Tenant struct {
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
// Global Agent configuration for this tenant (default for all sessions)
AgentConfig *AgentConfig `yaml:"agent_config" json:"agent_config" gorm:"type:json"`
// Global Context configuration for this tenant (default for all sessions)
ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:json"`
// Creation time
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time