diff --git a/frontend/src/api/chat/streame.ts b/frontend/src/api/chat/streame.ts
index 8b7d93ee..0b765e01 100644
--- a/frontend/src/api/chat/streame.ts
+++ b/frontend/src/api/chat/streame.ts
@@ -28,7 +28,7 @@ export function useStream() {
let renderTimer: number | null = null
// 启动流式请求
- const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string}>; method: string; url: string }) => {
+ const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string}>; method: string; url: string }) => {
// 重置状态
output.value = '';
error.value = null;
@@ -97,6 +97,10 @@ export function useStream() {
if (params.web_search_enabled !== undefined) {
postBody.web_search_enabled = params.web_search_enabled;
}
+ // Include enable_memory if provided
+ if (params.enable_memory !== undefined) {
+ postBody.enable_memory = params.enable_memory;
+ }
// Include summary_model_id if provided (for non-Agent mode)
if (params.summary_model_id) {
postBody.summary_model_id = params.summary_model_id;
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index d03fa232..c814dba7 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -501,6 +501,8 @@ export default {
conversationConfig: 'Conversation Settings',
conversationStrategy: 'Conversation Strategy',
webSearchConfig: 'Web Search',
+ enableMemory: 'Enable Memory',
+ enableMemoryDesc: 'When enabled, the system will record your conversation history and automatically recall relevant content in future conversations to provide more personalized answers.',
mcpService: 'MCP Service',
systemSettings: 'System Settings',
tenantInfo: 'Tenant Info',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 0e1735e3..0335af08 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -343,6 +343,8 @@ export default {
conversationConfig: "对话设置",
conversationStrategy: "对话策略",
webSearchConfig: "网络搜索",
+ enableMemory: "开启记忆功能",
+ enableMemoryDesc: "开启后,系统将记录您的对话历史,并在后续对话中自动回忆相关内容,提供更个性化的回答。",
mcpService: "MCP服务",
systemSettings: "系统设置",
tenantInfo: "租户信息",
diff --git a/frontend/src/stores/settings.ts b/frontend/src/stores/settings.ts
index 8daca0de..3aaed235 100644
--- a/frontend/src/stores/settings.ts
+++ b/frontend/src/stores/settings.ts
@@ -14,6 +14,7 @@ interface Settings {
modelConfig: ModelConfig; // 模型配置
ollamaConfig: OllamaConfig; // Ollama配置
webSearchEnabled: boolean; // 网络搜索是否启用
+ enableMemory: boolean; // 是否开启记忆功能
conversationModels: ConversationModels;
selectedAgentId: string; // 当前选中的智能体ID
selectedAgentSourceTenantId: string | null; // 当使用共享智能体时,来源租户 ID(用于后端 model/KB/MCP 解析)
@@ -86,6 +87,7 @@ const defaultSettings: Settings = {
enabled: true
},
webSearchEnabled: false, // 默认关闭网络搜索
+ enableMemory: false, // 默认关闭记忆功能
conversationModels: {
summaryModelId: "",
rerankModelId: "",
@@ -138,6 +140,9 @@ export const useSettingsStore = defineStore("settings", {
// 网络搜索是否启用
isWebSearchEnabled: (state) => state.settings.webSearchEnabled || false,
+ // 记忆功能是否启用
+ isMemoryEnabled: (state) => state.settings.enableMemory || false,
+
// 当前选中的智能体ID
selectedAgentId: (state) => state.settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID,
// 共享智能体来源租户 ID(可选)
@@ -296,6 +301,12 @@ export const useSettingsStore = defineStore("settings", {
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
},
+ // 启用/禁用记忆功能
+ toggleMemory(enabled: boolean) {
+ this.settings.enableMemory = enabled;
+ localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
+ },
+
// File selection actions
addFile(fileId: string) {
if (!this.settings.selectedFiles) this.settings.selectedFiles = [];
diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue
index 9537b422..2c6380b8 100644
--- a/frontend/src/views/chat/index.vue
+++ b/frontend/src/views/chat/index.vue
@@ -319,6 +319,9 @@ const sendMsg = async (value, modelId = '', mentionedItems = []) => {
// Get web search status from settings store
const webSearchEnabled = useSettingsStoreInstance.isWebSearchEnabled;
+ // Get memory status from settings store
+ const enableMemory = useSettingsStoreInstance.isMemoryEnabled;
+
// Get knowledge_base_ids from settings store (selected by user via KnowledgeBaseSelector)
// Merge @mentioned KB/file IDs so retrieval uses the same targets user @mentioned (including shared KBs)
const sidebarKbIds = useSettingsStoreInstance.settings.selectedKnowledgeBases || [];
@@ -352,6 +355,7 @@ const sendMsg = async (value, modelId = '', mentionedItems = []) => {
agent_enabled: agentEnabled,
agent_id: selectedAgentId,
web_search_enabled: webSearchEnabled,
+ enable_memory: enableMemory,
summary_model_id: modelId,
mcp_service_ids: mcpServiceIds,
mentioned_items: mentionedItems,
diff --git a/frontend/src/views/settings/GeneralSettings.vue b/frontend/src/views/settings/GeneralSettings.vue
index d71a1a5c..3e6edb16 100755
--- a/frontend/src/views/settings/GeneralSettings.vue
+++ b/frontend/src/views/settings/GeneralSettings.vue
@@ -26,6 +26,17 @@
+
+
+
+
+
+
{{ $t('settings.enableMemoryDesc') }}
+
+
+
+
+
@@ -34,13 +45,21 @@
import { ref, onMounted, computed } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
+import { useSettingsStore } from '@/stores/settings'
const { t, locale } = useI18n()
+const settingsStore = useSettingsStore()
// 本地状态
const localLanguage = ref('zh-CN')
const localTheme = ref('light')
+// 记忆功能状态
+const isMemoryEnabled = computed({
+ get: () => settingsStore.isMemoryEnabled,
+ set: (val) => settingsStore.toggleMemory(val)
+})
+
// 初始化加载
onMounted(() => {
// 从 localStorage 加载语言设置
@@ -60,6 +79,12 @@ const handleLanguageChange = () => {
MessagePlugin.success(t('language.languageSaved'))
}
+// 处理记忆功能变化
+const handleMemoryChange = (val: boolean) => {
+ settingsStore.toggleMemory(val)
+ MessagePlugin.success(t('common.success'))
+}
+
// 处理主题变化
const handleThemeChange = () => {
const settings = {
@@ -140,5 +165,4 @@ const handleThemeChange = () => {
justify-content: flex-end;
align-items: center;
}
-
-
+
\ No newline at end of file
diff --git a/internal/application/repository/memory/neo4j/repository.go b/internal/application/repository/memory/neo4j/repository.go
new file mode 100644
index 00000000..082b9e98
--- /dev/null
+++ b/internal/application/repository/memory/neo4j/repository.go
@@ -0,0 +1,148 @@
+package neo4j
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/neo4j/neo4j-go-driver/v6/neo4j"
+)
+
+type MemoryRepository struct {
+ driver neo4j.Driver
+}
+
+func NewMemoryRepository(driver neo4j.Driver) interfaces.MemoryRepository {
+ return &MemoryRepository{driver: driver}
+}
+
+func (r *MemoryRepository) IsAvailable(ctx context.Context) bool {
+ return r.driver != nil
+}
+
+func (r *MemoryRepository) SaveEpisode(ctx context.Context, episode *types.Episode, entities []*types.Entity, relations []*types.Relationship) error {
+ session := r.driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeWrite})
+ defer session.Close(ctx)
+
+ _, err := session.ExecuteWrite(ctx, func(tx neo4j.ManagedTransaction) (interface{}, error) {
+ // 1. Create Episode Node
+ createEpisodeQuery := `
+ MERGE (e:Episode {id: $id})
+ SET e.user_id = $user_id,
+ e.session_id = $session_id,
+ e.summary = $summary,
+ e.created_at = $created_at
+ `
+ _, err := tx.Run(ctx, createEpisodeQuery, map[string]interface{}{
+ "id": episode.ID,
+ "user_id": episode.UserID,
+ "session_id": episode.SessionID,
+ "summary": episode.Summary,
+ "created_at": episode.CreatedAt.Format(time.RFC3339),
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to create episode: %v", err)
+ }
+
+ // 2. Create Entity Nodes and MENTIONS relationships
+ for _, entity := range entities {
+ createEntityQuery := `
+ MERGE (n:Entity {name: $name})
+ SET n.type = $type,
+ n.description = $description
+ WITH n
+ MATCH (e:Episode {id: $episode_id})
+ MERGE (e)-[:MENTIONS]->(n)
+ `
+ _, err := tx.Run(ctx, createEntityQuery, map[string]interface{}{
+ "name": entity.Title,
+ "type": entity.Type,
+ "description": entity.Description,
+ "episode_id": episode.ID,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to create entity %s: %v", entity.Title, err)
+ }
+ }
+
+ // 3. Create Relationships between Entities
+ for _, rel := range relations {
+ createRelQuery := `
+ MATCH (s:Entity {name: $source})
+ MATCH (t:Entity {name: $target})
+ MERGE (s)-[r:RELATED_TO {description: $description}]->(t)
+ SET r.weight = $weight
+ `
+ _, err := tx.Run(ctx, createRelQuery, map[string]interface{}{
+ "source": rel.Source,
+ "target": rel.Target,
+ "description": rel.Description,
+ "weight": rel.Weight,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to create relationship between %s and %s: %v", rel.Source, rel.Target, err)
+ }
+ }
+
+ return nil, nil
+ })
+
+ if err != nil {
+ logger.Errorf(ctx, "failed to save episode: %v", err)
+ return err
+ }
+
+ return nil
+}
+
+func (r *MemoryRepository) FindRelatedEpisodes(ctx context.Context, userID string, keywords []string, limit int) ([]*types.Episode, error) {
+ session := r.driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeRead})
+ defer session.Close(ctx)
+
+ result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (interface{}, error) {
+ querySimple := `
+ MATCH (e:Episode)-[:MENTIONS]->(n:Entity)
+ WHERE e.user_id = $user_id AND n.name IN $keywords
+ RETURN DISTINCT e
+ ORDER BY e.created_at DESC
+ LIMIT $limit
+ `
+
+ res, err := tx.Run(ctx, querySimple, map[string]interface{}{
+ "user_id": userID,
+ "keywords": keywords,
+ "limit": limit,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ var episodes []*types.Episode
+ for res.Next(ctx) {
+ record := res.Record()
+ node, _ := record.Get("e")
+ episodeNode := node.(neo4j.Node)
+
+ createdAtStr := episodeNode.Props["created_at"].(string)
+ createdAt, _ := time.Parse(time.RFC3339, createdAtStr)
+
+ episodes = append(episodes, &types.Episode{
+ ID: episodeNode.Props["id"].(string),
+ UserID: episodeNode.Props["user_id"].(string),
+ SessionID: episodeNode.Props["session_id"].(string),
+ Summary: episodeNode.Props["summary"].(string),
+ CreatedAt: createdAt,
+ })
+ }
+ return episodes, nil
+ })
+
+ if err != nil {
+ return nil, err
+ }
+
+ return result.([]*types.Episode), nil
+}
diff --git a/internal/application/service/chat_pipline/memory.go b/internal/application/service/chat_pipline/memory.go
new file mode 100644
index 00000000..15bbf0f0
--- /dev/null
+++ b/internal/application/service/chat_pipline/memory.go
@@ -0,0 +1,148 @@
+package chatpipline
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/Tencent/WeKnora/internal/event"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+type MemoryPlugin struct {
+ memoryService interfaces.MemoryService
+}
+
+func NewMemoryPlugin(eventManager *EventManager, memoryService interfaces.MemoryService) *MemoryPlugin {
+ res := &MemoryPlugin{
+ memoryService: memoryService,
+ }
+ eventManager.Register(res)
+ return res
+}
+
+func (p *MemoryPlugin) ActivationEvents() []types.EventType {
+ return []types.EventType{
+ types.MEMORY_RETRIEVAL,
+ types.MEMORY_STORAGE,
+ }
+}
+
+func (p *MemoryPlugin) OnEvent(
+ ctx context.Context,
+ eventType types.EventType,
+ chatManage *types.ChatManage,
+ next func() *PluginError,
+) *PluginError {
+ switch eventType {
+ case types.MEMORY_RETRIEVAL:
+ return p.handleRetrieval(ctx, chatManage, next)
+ case types.MEMORY_STORAGE:
+ return p.handleStorage(ctx, chatManage, next)
+ default:
+ return next()
+ }
+}
+
+func (p *MemoryPlugin) handleRetrieval(
+ ctx context.Context,
+ chatManage *types.ChatManage,
+ next func() *PluginError,
+) *PluginError {
+ // Check if memory is enabled
+ if !chatManage.EnableMemory {
+ return next()
+ }
+ logger.Info(ctx, "Start to retrieve memory")
+
+ // Retrieve memory context
+ query := chatManage.RewriteQuery
+ if query == "" {
+ query = chatManage.Query
+ }
+
+ memoryContext, err := p.memoryService.RetrieveMemory(ctx, chatManage.UserID, query)
+ if err != nil {
+ logger.Errorf(ctx, "failed to retrieve memory: %v", err)
+ // Don't block the pipeline if memory retrieval fails
+ return next()
+ }
+
+ // Add memory context to chatManage
+ if len(memoryContext.RelatedEpisodes) > 0 {
+ memoryStr := "\n\nRelevant Memory:\n"
+ for _, ep := range memoryContext.RelatedEpisodes {
+ memoryStr += fmt.Sprintf("- %s (Summary: %s)\n", ep.CreatedAt.Format("2006-01-02"), ep.Summary)
+ }
+ chatManage.UserContent += memoryStr
+ logger.Info(ctx, "Retrieved memory: %s", memoryStr)
+ }
+ logger.Info(ctx, "End to retrieve memory")
+
+ return next()
+}
+
+func (p *MemoryPlugin) handleStorage(
+ ctx context.Context,
+ chatManage *types.ChatManage,
+ next func() *PluginError,
+) *PluginError {
+ if err := next(); err != nil {
+ return err
+ }
+
+ // Check if memory is enabled
+ if !chatManage.EnableMemory {
+ return nil
+ }
+
+ logger.Info(ctx, "Start to store memory")
+ // If ChatResponse is already available (non-streaming), store it directly
+ if chatManage.ChatResponse != nil {
+ messages := []types.Message{
+ {Role: "user", Content: chatManage.Query},
+ {Role: "assistant", Content: chatManage.ChatResponse.Content},
+ }
+ // Capture UserID and SessionID for goroutine
+ userID := chatManage.UserID
+ sessionID := chatManage.SessionID
+ go func() {
+ if err := p.memoryService.AddEpisode(ctx, userID, sessionID, messages); err != nil {
+ logger.Errorf(ctx, "failed to add episode: %v", err)
+ }
+ }()
+ return nil
+ }
+
+ // If streaming, subscribe to events
+ if chatManage.EventBus != nil {
+ var fullResponse string
+ // Capture UserID and SessionID for closure
+ userID := chatManage.UserID
+ sessionID := chatManage.SessionID
+
+ chatManage.EventBus.On(types.EventType(event.EventAgentFinalAnswer), func(ctx context.Context, evt types.Event) error {
+ data, ok := evt.Data.(event.AgentFinalAnswerData)
+ if !ok {
+ return nil
+ }
+ fullResponse += data.Content
+ if data.Done {
+ messages := []types.Message{
+ {Role: "user", Content: chatManage.Query},
+ {Role: "assistant", Content: fullResponse},
+ }
+ go func() {
+ if err := p.memoryService.AddEpisode(ctx, userID, sessionID, messages); err != nil {
+ logger.Errorf(ctx, "failed to add episode: %v", err)
+ }
+ }()
+ }
+ return nil
+ })
+ }
+ logger.Info(ctx, "End to store memory")
+
+ return nil
+}
diff --git a/internal/application/service/memory/service.go b/internal/application/service/memory/service.go
new file mode 100644
index 00000000..35be1e49
--- /dev/null
+++ b/internal/application/service/memory/service.go
@@ -0,0 +1,187 @@
+package memory
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/models/chat"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/Tencent/WeKnora/internal/utils"
+ "github.com/google/uuid"
+)
+
+// MemoryService implements the MemoryService interface
+type MemoryService struct {
+ repo interfaces.MemoryRepository
+ modelService interfaces.ModelService
+}
+
+// NewMemoryService creates a new memory service
+func NewMemoryService(repo interfaces.MemoryRepository, modelService interfaces.ModelService) interfaces.MemoryService {
+ return &MemoryService{
+ repo: repo,
+ modelService: modelService,
+ }
+}
+
+const extractGraphPrompt = `
+You are an AI assistant that extracts knowledge graphs from conversations.
+Given the following conversation, extract entities and relationships.
+Output the result in JSON format with the following structure:
+{
+ "summary": "A brief summary of the conversation",
+ "entities": [
+ {
+ "title": "Entity Name",
+ "type": "Entity Type (e.g., Person, Location, Concept)",
+ "description": "Description of the entity"
+ }
+ ],
+ "relationships": [
+ {
+ "source": "Source Entity Name",
+ "target": "Target Entity Name",
+ "description": "Description of the relationship",
+ "weight": 1.0
+ }
+ ]
+}
+
+Conversation:
+%s
+`
+
+const extractKeywordsPrompt = `
+You are an AI assistant that extracts search keywords from a user query.
+Given the following query, extract relevant keywords for searching a knowledge graph.
+Output the result in JSON format:
+{
+ "keywords": ["keyword1", "keyword2"]
+}
+
+Query:
+%s
+`
+
+type extractionResult struct {
+ Summary string `json:"summary" jsonschema:"a brief summary of the conversation"`
+ Entities []*types.Entity `json:"entities"`
+ Relationships []*types.Relationship `json:"relationships"`
+}
+
+type keywordsResult struct {
+ Keywords []string `json:"keywords" jsonschema:"relevant keywords for searching a knowledge graph"`
+}
+
+func (s *MemoryService) getChatModel(ctx context.Context) (chat.Chat, error) {
+ // Find the first available KnowledgeQA model
+ models, err := s.modelService.ListModels(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("failed to list models: %v", err)
+ }
+
+ var modelID string
+ for _, model := range models {
+ if model.Type == types.ModelTypeKnowledgeQA {
+ modelID = model.ID
+ break
+ }
+ }
+
+ if modelID == "" {
+ return nil, fmt.Errorf("no KnowledgeQA model found")
+ }
+
+ return s.modelService.GetChatModel(ctx, modelID)
+}
+
+// AddEpisode adds a new episode to the memory graph
+func (s *MemoryService) AddEpisode(ctx context.Context, userID string, sessionID string, messages []types.Message) error {
+ if !s.repo.IsAvailable(ctx) {
+ return fmt.Errorf("memory repository is not available")
+ }
+ chatModel, err := s.getChatModel(ctx)
+ if err != nil {
+ return err
+ }
+
+ // 1. Construct conversation string
+ var conversation string
+ for _, msg := range messages {
+ conversation += fmt.Sprintf("%s: %s\n", msg.Role, msg.Content)
+ }
+
+ // 2. Call LLM to extract graph
+ prompt := fmt.Sprintf(extractGraphPrompt, conversation)
+ resp, err := chatModel.Chat(ctx, []chat.Message{{Role: "user", Content: prompt}}, &chat.ChatOptions{
+ Format: utils.GenerateSchema[extractionResult](),
+ })
+ if err != nil {
+ return fmt.Errorf("failed to call LLM: %v", err)
+ }
+
+ var result extractionResult
+ if err := json.Unmarshal([]byte(resp.Content), &result); err != nil {
+ return fmt.Errorf("failed to parse LLM response: %v", err)
+ }
+
+ // 3. Create Episode object
+ episode := &types.Episode{
+ ID: uuid.New().String(),
+ UserID: userID,
+ SessionID: sessionID,
+ Summary: result.Summary,
+ CreatedAt: time.Now(),
+ }
+
+ // 4. Save to repository
+ if err := s.repo.SaveEpisode(ctx, episode, result.Entities, result.Relationships); err != nil {
+ return fmt.Errorf("failed to save episode: %v", err)
+ }
+
+ return nil
+}
+
+// RetrieveMemory retrieves relevant memory context based on the current query and user
+func (s *MemoryService) RetrieveMemory(ctx context.Context, userID string, query string) (*types.MemoryContext, error) {
+ if !s.repo.IsAvailable(ctx) {
+ return nil, fmt.Errorf("memory repository is not available")
+ }
+ chatModel, err := s.getChatModel(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ // 1. Extract keywords
+ prompt := fmt.Sprintf(extractKeywordsPrompt, query)
+ resp, err := chatModel.Chat(ctx, []chat.Message{{Role: "user", Content: prompt}}, &chat.ChatOptions{
+ Format: utils.GenerateSchema[keywordsResult](),
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to call LLM: %v", err)
+ }
+
+ var result keywordsResult
+ if err := json.Unmarshal([]byte(resp.Content), &result); err != nil {
+ return nil, fmt.Errorf("failed to parse LLM response: %v", err)
+ }
+
+ // 2. Retrieve related episodes
+ episodes, err := s.repo.FindRelatedEpisodes(ctx, userID, result.Keywords, 5)
+ if err != nil {
+ return nil, fmt.Errorf("failed to find related episodes: %v", err)
+ }
+
+ // 3. Construct MemoryContext
+ memoryContext := &types.MemoryContext{
+ RelatedEpisodes: make([]types.Episode, len(episodes)),
+ }
+ for i, ep := range episodes {
+ memoryContext.RelatedEpisodes[i] = *ep
+ }
+
+ return memoryContext, nil
+}
diff --git a/internal/application/service/session.go b/internal/application/service/session.go
index 30de72f5..e7c3daf4 100644
--- a/internal/application/service/session.go
+++ b/internal/application/service/session.go
@@ -44,6 +44,7 @@ type sessionService struct {
chunkService interfaces.ChunkService // Service for chunk operations
webSearchStateRepo interfaces.WebSearchStateService // Service for web search state
kbShareService interfaces.KBShareService // Service for KB sharing operations
+ memoryService interfaces.MemoryService // Service for memory operations
}
// NewSessionService creates a new session service instance with all required dependencies
@@ -60,6 +61,7 @@ func NewSessionService(cfg *config.Config,
sessionStorage llmcontext.ContextStorage,
webSearchStateRepo interfaces.WebSearchStateService,
kbShareService interfaces.KBShareService,
+ memoryService interfaces.MemoryService,
) interfaces.SessionService {
return &sessionService{
cfg: cfg,
@@ -75,6 +77,7 @@ func NewSessionService(cfg *config.Config,
sessionStorage: sessionStorage,
webSearchStateRepo: webSearchStateRepo,
kbShareService: kbShareService,
+ memoryService: memoryService,
}
}
@@ -443,13 +446,15 @@ func (s *sessionService) KnowledgeQA(
webSearchEnabled bool,
eventBus *event.EventBus,
customAgent *types.CustomAgent,
+ enableMemory bool,
) error {
logger.Infof(
ctx,
- "Knowledge base question answering parameters, session ID: %s, query: %s, webSearchEnabled: %v",
+ "Knowledge base question answering parameters, session ID: %s, query: %s, webSearchEnabled: %v, enableMemory: %v",
session.ID,
query,
webSearchEnabled,
+ enableMemory,
)
// Use custom agent's knowledge bases only if request didn't specify any
@@ -636,10 +641,15 @@ func (s *sessionService) KnowledgeQA(
chatModelID,
len(searchTargets),
)
+
+ // Get UserID from context
+ userID, _ := ctx.Value(types.UserIDContextKey).(string)
+
chatManage := &types.ChatManage{
Query: query,
RewriteQuery: query,
SessionID: session.ID,
+ UserID: userID,
MessageID: assistantMessageID, // NEW: For event emission in pipeline
KnowledgeBaseIDs: knowledgeBaseIDs, // Multi-KB support
KnowledgeIDs: knowledgeIDs, // Specific knowledge (file) IDs
@@ -658,6 +668,7 @@ func (s *sessionService) KnowledgeQA(
FallbackPrompt: fallbackPrompt,
EventBus: eventBus.AsEventBusInterface(), // NEW: For pipeline to emit events directly
WebSearchEnabled: webSearchEnabled,
+ EnableMemory: enableMemory, // Enable memory feature
TenantID: retrievalTenantID, // Effective tenant for retrieval (shared agent = agent's tenant)
RewritePromptSystem: rewritePromptSystem,
RewritePromptUser: rewritePromptUser,
@@ -1157,9 +1168,11 @@ func (s *sessionService) SearchKnowledge(ctx context.Context,
}
// Create default retrieval parameters
+ userID, _ := ctx.Value(types.UserIDContextKey).(string)
chatManage := &types.ChatManage{
Query: query,
RewriteQuery: query,
+ UserID: userID,
KnowledgeBaseIDs: knowledgeBaseIDs,
KnowledgeIDs: knowledgeIDs,
SearchTargets: searchTargets,
diff --git a/internal/container/container.go b/internal/container/container.go
index c1d7c4d0..63dec720 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -27,6 +27,7 @@ import (
"github.com/Tencent/WeKnora/docreader/client"
"github.com/Tencent/WeKnora/internal/application/repository"
+ memoryRepo "github.com/Tencent/WeKnora/internal/application/repository/memory/neo4j"
elasticsearchRepoV7 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v7"
elasticsearchRepoV8 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v8"
neo4jRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/neo4j"
@@ -36,6 +37,7 @@ import (
chatpipline "github.com/Tencent/WeKnora/internal/application/service/chat_pipline"
"github.com/Tencent/WeKnora/internal/application/service/file"
"github.com/Tencent/WeKnora/internal/application/service/llmcontext"
+ memoryService "github.com/Tencent/WeKnora/internal/application/service/memory"
"github.com/Tencent/WeKnora/internal/application/service/retriever"
"github.com/Tencent/WeKnora/internal/application/service/web_search"
"github.com/Tencent/WeKnora/internal/config"
@@ -109,6 +111,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(repository.NewUserRepository))
must(container.Provide(repository.NewAuthTokenRepository))
must(container.Provide(neo4jRepo.NewNeo4jRepository))
+ must(container.Provide(memoryRepo.NewMemoryRepository))
must(container.Provide(repository.NewMCPServiceRepository))
must(container.Provide(repository.NewCustomAgentRepository))
must(container.Provide(repository.NewOrganizationRepository))
@@ -144,6 +147,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(service.NewMessageService))
must(container.Provide(service.NewMCPServiceService))
must(container.Provide(service.NewCustomAgentService))
+ must(container.Provide(memoryService.NewMemoryService))
// Web search service (needed by AgentService)
logger.Debugf(ctx, "[Container] Registering web search registry and providers...")
@@ -184,6 +188,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Invoke(chatpipline.NewPluginExtractEntity))
must(container.Invoke(chatpipline.NewPluginSearchEntity))
must(container.Invoke(chatpipline.NewPluginSearchParallel))
+ must(container.Invoke(chatpipline.NewMemoryPlugin))
logger.Debugf(ctx, "[Container] Chat pipeline plugins registered")
// HTTP handlers layer
diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go
index 651101b6..617648a1 100644
--- a/internal/handler/session/qa.go
+++ b/internal/handler/session/qa.go
@@ -30,6 +30,7 @@ type qaRequestContext struct {
knowledgeIDs []string
summaryModelID string
webSearchEnabled bool
+ enableMemory bool // Whether memory feature is enabled
mentionedItems types.MentionedItems
effectiveTenantID uint64 // when using shared agent, tenant ID for model/KB/MCP resolution; 0 = use context tenant
}
@@ -166,6 +167,7 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
knowledgeIDs: secutils.SanitizeForLogArray(knowledgeIDs),
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
webSearchEnabled: request.WebSearchEnabled,
+ enableMemory: request.EnableMemory,
mentionedItems: convertMentionedItems(request.MentionedItems),
effectiveTenantID: effectiveTenantID,
}
@@ -449,6 +451,7 @@ func (h *Handler) executeNormalModeQA(reqCtx *qaRequestContext, generateTitle bo
reqCtx.webSearchEnabled,
streamCtx.eventBus,
reqCtx.customAgent,
+ reqCtx.enableMemory,
)
if err != nil {
logger.ErrorWithFields(streamCtx.asyncCtx, err, nil)
diff --git a/internal/handler/session/types.go b/internal/handler/session/types.go
index a1c24a0a..50affbf3 100644
--- a/internal/handler/session/types.go
+++ b/internal/handler/session/types.go
@@ -38,6 +38,7 @@ type CreateKnowledgeQARequest struct {
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
MentionedItems []MentionedItemRequest `json:"mentioned_items"` // @mentioned knowledge bases and files
DisableTitle bool `json:"disable_title"` // Whether to disable auto title generation
+ EnableMemory bool `json:"enable_memory"` // Whether memory feature is enabled for this request
}
// SearchKnowledgeRequest defines the request structure for searching knowledge without LLM summarization
diff --git a/internal/types/chat_manage.go b/internal/types/chat_manage.go
index db00f780..9ffb1c51 100644
--- a/internal/types/chat_manage.go
+++ b/internal/types/chat_manage.go
@@ -4,8 +4,10 @@ package types
// including query processing, search parameters, and model configurations
type ChatManage struct {
SessionID string `json:"session_id"` // Unique identifier for the chat session
+ UserID string `json:"user_id"` // Unique identifier for the user
Query string `json:"query,omitempty"` // Original user query
RewriteQuery string `json:"rewrite_query,omitempty"` // Query after rewriting for better retrieval
+ EnableMemory bool `json:"enable_memory"` // Whether memory feature is enabled
History []*History `json:"history,omitempty"` // Chat history for context
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // IDs of knowledge bases to search (multi-KB support)
@@ -147,6 +149,8 @@ const (
CHAT_COMPLETION_STREAM EventType = "chat_completion_stream" // Stream chat completion
STREAM_FILTER EventType = "stream_filter" // Filter streaming output
FILTER_TOP_K EventType = "filter_top_k" // Keep only top K results
+ MEMORY_RETRIEVAL EventType = "memory_retrieval" // Retrieve memory context
+ MEMORY_STORAGE EventType = "memory_storage" // Store conversation to memory
)
// Pipline defines the sequence of events for different chat modes
@@ -160,8 +164,10 @@ var Pipline = map[string][]EventType{
},
"chat_history_stream": { // Streaming chat with conversation history
LOAD_HISTORY,
+ MEMORY_RETRIEVAL,
CHAT_COMPLETION_STREAM,
STREAM_FILTER,
+ MEMORY_STORAGE,
},
"rag": { // Retrieval Augmented Generation
CHUNK_SEARCH,
diff --git a/internal/types/graph.go b/internal/types/graph.go
index e3f750ad..d50e68b9 100644
--- a/internal/types/graph.go
+++ b/internal/types/graph.go
@@ -8,24 +8,24 @@ import "context"
type Entity struct {
ID string // Unique identifier for the entity
ChunkIDs []string // References to document chunks where this entity appears
- Frequency int `json:"-"` // Number of occurrences in the corpus
- Degree int `json:"-"` // Number of connections to other entities
- Title string `json:"title"` // Display name of the entity
- Type string `json:"type"` // Classification of the entity (e.g., person, concept, organization)
- Description string `json:"description"` // Brief explanation or context about the entity
+ Frequency int `json:"-"` // Number of occurrences in the corpus
+ Degree int `json:"-"` // Number of connections to other entities
+ Title string `json:"title" jsonschema:"display name of the entity"` // Display name of the entity
+ Type string `json:"type" jsonschema:"type of the entity"` // Classification of the entity (e.g., person, concept, organization)
+ Description string `json:"description" jsonschema:"brief explanation or context about the entity"` // Brief explanation or context about the entity
}
// Relationship represents a connection between two entities in the knowledge graph.
// It captures the semantic connection between entities identified in the document chunks.
type Relationship struct {
- ID string `json:"-"` // Unique identifier for the relationship
- ChunkIDs []string `json:"-"` // References to document chunks where this relationship is established
- CombinedDegree int `json:"-"` // Sum of degrees of the connected entities, used for ranking
- Weight float64 `json:"-"` // Strength of the relationship based on textual evidence
- Source string `json:"source"` // ID of the entity where the relationship starts
- Target string `json:"target"` // ID of the entity where the relationship ends
- Description string `json:"description"` // Description of how these entities are related
- Strength int `json:"strength"` // Normalized measure of relationship importance (1-10)
+ ID string `json:"-"` // Unique identifier for the relationship
+ ChunkIDs []string `json:"-"` // References to document chunks where this relationship is established
+ CombinedDegree int `json:"-"` // Sum of degrees of the connected entities, used for ranking
+ Weight float64 `json:"-"` // Strength of the relationship based on textual evidence
+ Source string `json:"source" jsonschema:"ID of the entity where the relationship starts"` // ID of the entity where the relationship starts
+ Target string `json:"target" jsonschema:"ID of the entity where the relationship ends"` // ID of the entity where the relationship ends
+ Description string `json:"description" jsonschema:"description of how these entities are related"` // Description of how these entities are related
+ Strength int `json:"strength" jsonschema:"normalized measure of relationship importance (1-10)"` // Normalized measure of relationship importance (1-10)
}
// GraphBuilder defines the interface for building and querying the knowledge graph.
diff --git a/internal/types/interfaces/memory.go b/internal/types/interfaces/memory.go
new file mode 100644
index 00000000..1acfa9d9
--- /dev/null
+++ b/internal/types/interfaces/memory.go
@@ -0,0 +1,28 @@
+package interfaces
+
+import (
+ "context"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// MemoryService defines the interface for the memory system
+type MemoryService interface {
+ // AddEpisode processes a conversation session and adds it as an episode to the memory graph
+ AddEpisode(ctx context.Context, userID string, sessionID string, messages []types.Message) error
+
+ // RetrieveMemory retrieves relevant memory context based on the current query and user
+ RetrieveMemory(ctx context.Context, userID string, query string) (*types.MemoryContext, error)
+}
+
+// MemoryRepository defines the interface for storing and retrieving memory data
+type MemoryRepository interface {
+ // SaveEpisode saves an episode and its associated entities and relationships to the graph
+ SaveEpisode(ctx context.Context, episode *types.Episode, entities []*types.Entity, relations []*types.Relationship) error
+
+ // FindRelatedEpisodes finds episodes related to the given keywords for a specific user
+ FindRelatedEpisodes(ctx context.Context, userID string, keywords []string, limit int) ([]*types.Episode, error)
+
+ // IsAvailable checks if the memory repository is available
+ IsAvailable(ctx context.Context) bool
+}
diff --git a/internal/types/interfaces/session.go b/internal/types/interfaces/session.go
index 264ee6809..1a4b9b22 100644
--- a/internal/types/interfaces/session.go
+++ b/internal/types/interfaces/session.go
@@ -36,11 +36,12 @@ type SessionService interface {
// summaryModelID: optional summary model ID override (if empty, uses session/KB default)
// webSearchEnabled: whether to enable web search to supplement knowledge base results
// customAgent: optional custom agent for config override (multiTurnEnabled, historyTurns)
+ // enableMemory: whether to enable memory feature for this request
// Events are emitted through eventBus (references, answer chunks, completion)
KnowledgeQA(ctx context.Context,
session *types.Session, query string, knowledgeBaseIDs []string, knowledgeIDs []string,
assistantMessageID string, summaryModelID string, webSearchEnabled bool, eventBus *event.EventBus,
- customAgent *types.CustomAgent,
+ customAgent *types.CustomAgent, enableMemory bool,
) error
// KnowledgeQAByEvent performs knowledge-based question answering by event
KnowledgeQAByEvent(ctx context.Context, chatManage *types.ChatManage, eventList []types.EventType) error
diff --git a/internal/types/memory.go b/internal/types/memory.go
new file mode 100644
index 00000000..898d258e
--- /dev/null
+++ b/internal/types/memory.go
@@ -0,0 +1,19 @@
+package types
+
+import "time"
+
+// Episode represents a conversation episode or a distinct interaction event
+type Episode struct {
+ ID string `json:"id"`
+ UserID string `json:"user_id"`
+ SessionID string `json:"session_id"`
+ Summary string `json:"summary"`
+ CreatedAt time.Time `json:"created_at"`
+}
+
+// MemoryContext represents the retrieved memory context for a conversation
+type MemoryContext struct {
+ RelatedEpisodes []Episode `json:"related_episodes"`
+ RelatedEntities []Entity `json:"related_entities"`
+ RelatedRelations []Relationship `json:"related_relations"`
+}