refactor: Enhance chat message handling and session management
- Updated chat message sending logic to conditionally validate knowledge base IDs based on agent mode status. - Improved endpoint selection for chat requests, allowing for dynamic routing between agent and knowledge chat. - Introduced a new method to select the appropriate chat model ID, prioritizing remote models for enhanced flexibility. - Changed JSON column types for agent and context configurations in session and tenant types to jsonb for better performance.
This commit is contained in:
@@ -227,12 +227,14 @@ const sendMsg = async (value) => {
|
|||||||
messagesList.push({ content: value, role: 'user' });
|
messagesList.push({ content: value, role: 'user' });
|
||||||
scrollToBottom();
|
scrollToBottom();
|
||||||
|
|
||||||
// Always use agent mode with unified architecture
|
// Get agent mode status from settings store
|
||||||
|
const agentEnabled = useSettingsStoreInstance.isAgentEnabled;
|
||||||
|
|
||||||
// Get knowledge_base_ids from settings store (selected by user via KnowledgeBaseSelector)
|
// Get knowledge_base_ids from settings store (selected by user via KnowledgeBaseSelector)
|
||||||
const kbIds = useSettingsStoreInstance.settings.selectedKnowledgeBases || [];
|
const kbIds = useSettingsStoreInstance.settings.selectedKnowledgeBases || [];
|
||||||
|
|
||||||
// Validate knowledge_base_ids before sending
|
// Validate knowledge_base_ids before sending (only when agent mode is enabled)
|
||||||
if (kbIds.length === 0) {
|
if (agentEnabled && kbIds.length === 0) {
|
||||||
MessagePlugin.warning('请至少选择一个知识库');
|
MessagePlugin.warning('请至少选择一个知识库');
|
||||||
isReplying.value = false;
|
isReplying.value = false;
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
@@ -241,13 +243,16 @@ const sendMsg = async (value) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Use agent-chat endpoint when agent is enabled, otherwise use knowledge-chat
|
||||||
|
const endpoint = agentEnabled ? '/api/v1/agent-chat' : '/api/v1/knowledge-chat';
|
||||||
|
|
||||||
await startStream({
|
await startStream({
|
||||||
session_id: session_id.value,
|
session_id: session_id.value,
|
||||||
knowledge_base_ids: kbIds,
|
knowledge_base_ids: kbIds,
|
||||||
agent_enabled: true,
|
agent_enabled: agentEnabled,
|
||||||
query: value,
|
query: value,
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
url: '/api/v1/agent-chat'
|
url: endpoint
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -411,8 +411,14 @@ func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Session
|
|||||||
|
|
||||||
logger.Infof(ctx, "Using knowledge bases: %v", knowledgeBaseIDs)
|
logger.Infof(ctx, "Using knowledge bases: %v", knowledgeBaseIDs)
|
||||||
|
|
||||||
|
// Determine chat model ID: prioritize Remote models
|
||||||
|
chatModelID, err := s.selectChatModelID(ctx, session, knowledgeBaseIDs)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
// Create chat management object with session settings
|
// Create chat management object with session settings
|
||||||
logger.Infof(ctx, "Creating chat manage object, knowledge base IDs: %v", knowledgeBaseIDs)
|
logger.Infof(ctx, "Creating chat manage object, knowledge base IDs: %v, chat model ID: %s", knowledgeBaseIDs, chatModelID)
|
||||||
chatManage := &types.ChatManage{
|
chatManage := &types.ChatManage{
|
||||||
Query: query,
|
Query: query,
|
||||||
RewriteQuery: query,
|
RewriteQuery: query,
|
||||||
@@ -425,7 +431,7 @@ func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Session
|
|||||||
RerankModelID: session.RerankModelID,
|
RerankModelID: session.RerankModelID,
|
||||||
RerankTopK: session.RerankTopK,
|
RerankTopK: session.RerankTopK,
|
||||||
RerankThreshold: session.RerankThreshold,
|
RerankThreshold: session.RerankThreshold,
|
||||||
ChatModelID: session.SummaryModelID,
|
ChatModelID: chatModelID,
|
||||||
SummaryConfig: types.SummaryConfig{
|
SummaryConfig: types.SummaryConfig{
|
||||||
MaxTokens: session.SummaryParameters.MaxTokens,
|
MaxTokens: session.SummaryParameters.MaxTokens,
|
||||||
RepeatPenalty: session.SummaryParameters.RepeatPenalty,
|
RepeatPenalty: session.SummaryParameters.RepeatPenalty,
|
||||||
@@ -445,7 +451,7 @@ func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Session
|
|||||||
|
|
||||||
// Start knowledge QA event processing
|
// Start knowledge QA event processing
|
||||||
logger.Info(ctx, "Triggering knowledge base question answering event")
|
logger.Info(ctx, "Triggering knowledge base question answering event")
|
||||||
err := s.KnowledgeQAByEvent(ctx, chatManage, types.Pipline["rag_stream"])
|
err = s.KnowledgeQAByEvent(ctx, chatManage, types.Pipline["rag_stream"])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||||
"session_id": session.ID,
|
"session_id": session.ID,
|
||||||
@@ -458,6 +464,80 @@ func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Session
|
|||||||
return chatManage.MergeResult, chatManage.ResponseChan, nil
|
return chatManage.MergeResult, chatManage.ResponseChan, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// selectChatModelID selects the appropriate chat model ID with priority for Remote models
|
||||||
|
// Priority order:
|
||||||
|
// 1. Session's SummaryModelID if it's a Remote model
|
||||||
|
// 2. First knowledge base with a Remote model
|
||||||
|
// 3. Session's SummaryModelID (if not Remote)
|
||||||
|
// 4. First knowledge base's SummaryModelID
|
||||||
|
func (s *sessionService) selectChatModelID(ctx context.Context, session *types.Session, knowledgeBaseIDs []string) (string, error) {
|
||||||
|
chatModelID := ""
|
||||||
|
|
||||||
|
// First, check if session has a SummaryModelID and if it's a Remote model
|
||||||
|
if session.SummaryModelID != "" {
|
||||||
|
model, err := s.modelService.GetModelByID(ctx, session.SummaryModelID)
|
||||||
|
if err == nil && model != nil && model.Source == types.ModelSourceRemote {
|
||||||
|
chatModelID = session.SummaryModelID
|
||||||
|
logger.Infof(ctx, "Using session's Remote summary model: %s", chatModelID)
|
||||||
|
return chatModelID, nil
|
||||||
|
} else if err == nil && model != nil {
|
||||||
|
// Session has a model but it's not Remote, we'll check knowledge bases for Remote models
|
||||||
|
logger.Infof(ctx, "Session has summary model %s but it's not Remote, checking knowledge bases for Remote models", session.SummaryModelID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no Remote model found from session, check knowledge bases for Remote models
|
||||||
|
if chatModelID == "" && len(knowledgeBaseIDs) > 0 {
|
||||||
|
// Try to find a knowledge base with Remote model
|
||||||
|
for _, kbID := range knowledgeBaseIDs {
|
||||||
|
kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, kbID)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warnf(ctx, "Failed to get knowledge base %s: %v", kbID, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if kb != nil && kb.SummaryModelID != "" {
|
||||||
|
model, err := s.modelService.GetModelByID(ctx, kb.SummaryModelID)
|
||||||
|
if err == nil && model != nil && model.Source == types.ModelSourceRemote {
|
||||||
|
chatModelID = kb.SummaryModelID
|
||||||
|
logger.Infof(ctx, "Using Remote summary model from knowledge base %s: %s", kbID, chatModelID)
|
||||||
|
return chatModelID, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If still no Remote model found, use session's SummaryModelID if available
|
||||||
|
if chatModelID == "" && session.SummaryModelID != "" {
|
||||||
|
chatModelID = session.SummaryModelID
|
||||||
|
logger.Infof(ctx, "No Remote model found, using session's summary model: %s", chatModelID)
|
||||||
|
return chatModelID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// If still empty, use first knowledge base's model
|
||||||
|
if chatModelID == "" {
|
||||||
|
kb, err := s.knowledgeBaseService.GetKnowledgeBaseByID(ctx, knowledgeBaseIDs[0])
|
||||||
|
if err != nil {
|
||||||
|
logger.Errorf(ctx, "Failed to get knowledge base for model ID: %v", err)
|
||||||
|
return "", fmt.Errorf("failed to get knowledge base %s: %w", knowledgeBaseIDs[0], err)
|
||||||
|
}
|
||||||
|
if kb != nil && kb.SummaryModelID != "" {
|
||||||
|
chatModelID = kb.SummaryModelID
|
||||||
|
logger.Infof(ctx, "Using summary model from first knowledge base %s: %s", knowledgeBaseIDs[0], chatModelID)
|
||||||
|
return chatModelID, nil
|
||||||
|
} else {
|
||||||
|
logger.Errorf(ctx, "Knowledge base %s has no summary model ID", knowledgeBaseIDs[0])
|
||||||
|
return "", fmt.Errorf("knowledge base %s has no summary model configured", knowledgeBaseIDs[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if chatModelID == "" {
|
||||||
|
logger.Error(ctx, "No chat model ID available")
|
||||||
|
return "", errors.New("no chat model ID available: session has no SummaryModelID and knowledge bases have no SummaryModelID")
|
||||||
|
}
|
||||||
|
|
||||||
|
return chatModelID, nil
|
||||||
|
}
|
||||||
|
|
||||||
// KnowledgeQAByEvent processes knowledge QA through a series of events in the pipeline
|
// KnowledgeQAByEvent processes knowledge QA through a series of events in the pipeline
|
||||||
func (s *sessionService) KnowledgeQAByEvent(ctx context.Context,
|
func (s *sessionService) KnowledgeQAByEvent(ctx context.Context,
|
||||||
chatManage *types.ChatManage, eventList []types.EventType,
|
chatManage *types.ChatManage, eventList []types.EventType,
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ type Message struct {
|
|||||||
// Agent execution steps (only for assistant messages generated by agent)
|
// Agent execution steps (only for assistant messages generated by agent)
|
||||||
// This contains the detailed reasoning process and tool calls made by the agent
|
// This contains the detailed reasoning process and tool calls made by the agent
|
||||||
// Stored for user history display, but NOT included in LLM context to avoid redundancy
|
// Stored for user history display, but NOT included in LLM context to avoid redundancy
|
||||||
AgentSteps AgentSteps `json:"agent_steps,omitempty" gorm:"type:json,column:agent_steps"`
|
AgentSteps AgentSteps `json:"agent_steps,omitempty" gorm:"type:jsonb,column:agent_steps"`
|
||||||
// Whether message generation is complete
|
// Whether message generation is complete
|
||||||
IsCompleted bool `json:"is_completed"`
|
IsCompleted bool `json:"is_completed"`
|
||||||
// Message creation timestamp
|
// Message creation timestamp
|
||||||
|
|||||||
@@ -93,8 +93,8 @@ type Session struct {
|
|||||||
RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值
|
RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值
|
||||||
SummaryModelID string `json:"summary_model_id"` // 总结模型ID
|
SummaryModelID string `json:"summary_model_id"` // 总结模型ID
|
||||||
SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数
|
SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数
|
||||||
AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:json"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases)
|
AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:jsonb"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases)
|
||||||
ContextConfig *ContextConfig `json:"context_config" gorm:"type:json"` // 上下文管理配置(可选)
|
ContextConfig *ContextConfig `json:"context_config" gorm:"type:jsonb"` // 上下文管理配置(可选)
|
||||||
|
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
|||||||
@@ -29,9 +29,9 @@ type Tenant struct {
|
|||||||
// Storage used (Bytes)
|
// Storage used (Bytes)
|
||||||
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
|
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
|
||||||
// Global Agent configuration for this tenant (default for all sessions)
|
// Global Agent configuration for this tenant (default for all sessions)
|
||||||
AgentConfig *AgentConfig `yaml:"agent_config" json:"agent_config" gorm:"type:json"`
|
AgentConfig *AgentConfig `yaml:"agent_config" json:"agent_config" gorm:"type:jsonb"`
|
||||||
// Global Context configuration for this tenant (default for all sessions)
|
// Global Context configuration for this tenant (default for all sessions)
|
||||||
ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:json"`
|
ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:jsonb"`
|
||||||
// Creation time
|
// Creation time
|
||||||
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
|
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
|
||||||
// Last updated time
|
// Last updated time
|
||||||
|
|||||||
Reference in New Issue
Block a user