feat: implement preview of user level memory graph

Signed-off-by: joeyczheng <joeyczheng@tencent.com>
This commit is contained in:
joeyczheng
2026-02-12 16:02:09 +08:00
committed by lyingbug
parent 6adecdb30e
commit 12baa885d2
18 changed files with 624 additions and 18 deletions
@@ -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
}
@@ -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
}
+14 -1
View File
@@ -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,