feat: implement preview of user level memory graph
Signed-off-by: joeyczheng <joeyczheng@tencent.com>
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user