Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
refactor: Enhance chat message handling and session management
wizardchen655df49d7d32
diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vueindex 52e6694a6..04e461ffa 100644--- a/frontend/src/views/chat/index.vue+++ b/frontend/src/views/chat/index.vue@@ -227,12 +227,14 @@ const sendMsg = async (value) => {messagesList.push({ content: value, role: 'user' });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)const kbIds = useSettingsStoreInstance.settings.selectedKnowledgeBases || [];- // Validate knowledge_base_ids before sending- if (kbIds.length === 0) {+ // Validate knowledge_base_ids before sending (only when agent mode is enabled)+ if (agentEnabled && kbIds.length === 0) {MessagePlugin.warning('请至少选择一个知识库');isReplying.value = false;loading.value = false;@@ -241,13 +243,16 @@ const sendMsg = async (value) => {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({session_id: session_id.value,knowledge_base_ids: kbIds,- agent_enabled: true,+ agent_enabled: agentEnabled,query: value,method: 'POST',- url: '/api/v1/agent-chat'+ url: endpoint});}diff --git a/internal/application/service/session.go b/internal/application/service/session.goindex 1b26547cf..784031db9 100644--- a/internal/application/service/session.go+++ b/internal/application/service/session.go@@ -411,8 +411,14 @@ func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Sessionlogger.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- 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{Query: query,RewriteQuery: query,@@ -425,7 +431,7 @@ func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.SessionRerankModelID: session.RerankModelID,RerankTopK: session.RerankTopK,RerankThreshold: session.RerankThreshold,- ChatModelID: session.SummaryModelID,+ ChatModelID: chatModelID,SummaryConfig: types.SummaryConfig{MaxTokens: session.SummaryParameters.MaxTokens,RepeatPenalty: session.SummaryParameters.RepeatPenalty,@@ -445,7 +451,7 @@ func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Session// Start knowledge QA event processinglogger.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 {logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": session.ID,@@ -458,6 +464,80 @@ func (s *sessionService) KnowledgeQA(ctx context.Context, session *types.Sessionreturn 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 pipelinefunc (s *sessionService) KnowledgeQAByEvent(ctx context.Context,chatManage *types.ChatManage, eventList []types.EventType,diff --git a/internal/types/message.go b/internal/types/message.goindex c54490dae..56fc29da3 100644--- a/internal/types/message.go+++ b/internal/types/message.go@@ -39,7 +39,7 @@ type Message struct {// Agent execution steps (only for assistant messages generated by 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- 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 completeIsCompleted bool `json:"is_completed"`// Message creation timestampdiff --git a/internal/types/session.go b/internal/types/session.goindex c9c2c946d..9f339d069 100644--- a/internal/types/session.go+++ b/internal/types/session.go@@ -93,8 +93,8 @@ type Session struct {RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值SummaryModelID string `json:"summary_model_id"` // 总结模型IDSummaryParameters *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"` // 上下文管理配置(可选)+ AgentConfig *SessionAgentConfig `json:"agent_config" gorm:"type:jsonb"` // Agent 配置(会话级别,仅存储enabled和knowledge_bases)+ ContextConfig *ContextConfig `json:"context_config" gorm:"type:jsonb"` // 上下文管理配置(可选)CreatedAt time.Time `json:"created_at"`UpdatedAt time.Time `json:"updated_at"`diff --git a/internal/types/tenant.go b/internal/types/tenant.goindex ee589ccc6..edf510c40 100644--- a/internal/types/tenant.go+++ b/internal/types/tenant.go@@ -29,9 +29,9 @@ type Tenant struct {// Storage used (Bytes)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"`+ 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:json"`+ ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:jsonb"`// Creation timeCreatedAt time.Time `yaml:"created_at" json:"created_at"`// Last updated time