refactor: remove Neo4j-based conversation memory feature
Drop the memory pipeline, API fields, settings UI, and embed toggles so chat no longer depends on Neo4j graph storage for episodic recall.
This commit is contained in:
@@ -1,148 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
package chatpipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"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.Infof(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},
|
||||
}
|
||||
userID := chatManage.UserID
|
||||
sessionID := chatManage.SessionID
|
||||
bgCtx := context.WithoutCancel(ctx)
|
||||
go func() {
|
||||
if err := p.memoryService.AddEpisode(bgCtx, userID, sessionID, messages); err != nil {
|
||||
logger.Errorf(bgCtx, "failed to add episode: %v", err)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// If streaming, subscribe to events
|
||||
if chatManage.EventBus != nil {
|
||||
var fullResponse string
|
||||
var storeOnce sync.Once
|
||||
userID := chatManage.UserID
|
||||
sessionID := chatManage.SessionID
|
||||
bgCtx := context.WithoutCancel(ctx)
|
||||
|
||||
chatManage.EventBus.On(types.EventType(event.EventAgentFinalAnswer), func(_ context.Context, evt types.Event) error {
|
||||
data, ok := evt.Data.(event.AgentFinalAnswerData)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
fullResponse += data.Content
|
||||
if data.Done {
|
||||
// Stream layer may emit Done:true twice (e.g. finish_reason chunk + EOF sentinel).
|
||||
// qa.go dedupes with completionHandled; keep memory writes consistent with one episode only.
|
||||
storeOnce.Do(func() {
|
||||
messages := []types.Message{
|
||||
{Role: "user", Content: chatManage.Query},
|
||||
{Role: "assistant", Content: fullResponse},
|
||||
}
|
||||
go func() {
|
||||
if err := p.memoryService.AddEpisode(bgCtx, userID, sessionID, messages); err != nil {
|
||||
logger.Errorf(bgCtx, "failed to add episode: %v", err)
|
||||
}
|
||||
}()
|
||||
})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
logger.Info(ctx, "End to store memory")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -85,7 +85,6 @@ func (s *embedChannelService) Create(
|
||||
ShowSuggestedQuestions: req.ShowSuggestedQuestions,
|
||||
WidgetPosition: types.NormalizeEmbedWidgetPosition(req.WidgetPosition),
|
||||
AllowWebSearch: req.AllowWebSearch,
|
||||
AllowMemory: req.AllowMemory,
|
||||
AllowFileUpload: req.AllowFileUpload,
|
||||
DefaultLocale: types.NormalizeEmbedDefaultLocale(req.DefaultLocale),
|
||||
}
|
||||
@@ -119,7 +118,7 @@ func (s *embedChannelService) ListByTenant(
|
||||
|
||||
func (s *embedChannelService) Update(
|
||||
ctx context.Context, tenantID uint64, id string, req *types.EmbedChannel,
|
||||
enabled *bool, showSuggested *bool, allowWebSearch *bool, allowMemory *bool, allowFileUpload *bool,
|
||||
enabled *bool, showSuggested *bool, allowWebSearch *bool, allowFileUpload *bool,
|
||||
defaultLocale *string, webhookURL *string, webhookSecret *string,
|
||||
) (*types.EmbedChannel, error) {
|
||||
ch, err := s.getOwned(ctx, tenantID, id)
|
||||
@@ -139,9 +138,6 @@ func (s *embedChannelService) Update(
|
||||
if allowWebSearch != nil {
|
||||
ch.AllowWebSearch = *allowWebSearch
|
||||
}
|
||||
if allowMemory != nil {
|
||||
ch.AllowMemory = *allowMemory
|
||||
}
|
||||
if allowFileUpload != nil {
|
||||
ch.AllowFileUpload = *allowFileUpload
|
||||
}
|
||||
@@ -262,7 +258,6 @@ func (s *embedChannelService) PublicConfig(ctx context.Context, ch *types.EmbedC
|
||||
AllowedOrigins: ch.AllowedOriginsList(),
|
||||
WidgetPosition: types.NormalizeEmbedWidgetPosition(ch.WidgetPosition),
|
||||
AllowWebSearch: ch.AllowWebSearch,
|
||||
AllowMemory: ch.AllowMemory,
|
||||
AllowFileUpload: ch.AllowFileUpload,
|
||||
AgentWebSearchEnabled: agentWebSearchEnabled,
|
||||
AgentImageUploadEnabled: agentImageUploadEnabled,
|
||||
|
||||
@@ -101,15 +101,11 @@ func TestPublicConfigIncludesCapabilityFlags(t *testing.T) {
|
||||
ID: "ch-cap",
|
||||
AgentID: "agent-cap",
|
||||
AllowWebSearch: true,
|
||||
AllowMemory: true,
|
||||
WidgetPosition: "top-left",
|
||||
})
|
||||
if !cfg.AllowWebSearch {
|
||||
t.Fatalf("allow_web_search = false, want true")
|
||||
}
|
||||
if !cfg.AllowMemory {
|
||||
t.Fatalf("allow_memory = false, want true")
|
||||
}
|
||||
if !cfg.AgentWebSearchEnabled {
|
||||
t.Fatalf("agent_web_search_enabled = false, want true")
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ func TestEmbedChannelUpdateAgentID(t *testing.T) {
|
||||
42,
|
||||
"ch-1",
|
||||
&types.EmbedChannel{AgentID: "agent-new"},
|
||||
&enabled, nil, nil, nil, nil, nil, nil, nil,
|
||||
&enabled, nil, nil, nil, nil, nil, nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Update() error = %v", err)
|
||||
|
||||
@@ -1,187 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -45,7 +45,6 @@ type sessionService struct {
|
||||
webSearchStateRepo interfaces.WebSearchStateService // Service for web search state
|
||||
webSearchProviderRepo interfaces.WebSearchProviderRepository // Repository for web search provider entities
|
||||
kbShareService interfaces.KBShareService // Service for KB sharing operations
|
||||
memoryService interfaces.MemoryService // Service for memory operations
|
||||
suggestionRepo interfaces.MessageSuggestionRepository
|
||||
}
|
||||
|
||||
@@ -63,7 +62,6 @@ func NewSessionService(cfg *config.Config,
|
||||
webSearchStateRepo interfaces.WebSearchStateService,
|
||||
webSearchProviderRepo interfaces.WebSearchProviderRepository,
|
||||
kbShareService interfaces.KBShareService,
|
||||
memoryService interfaces.MemoryService,
|
||||
suggestionRepo interfaces.MessageSuggestionRepository,
|
||||
) interfaces.SessionService {
|
||||
return &sessionService{
|
||||
@@ -80,7 +78,6 @@ func NewSessionService(cfg *config.Config,
|
||||
webSearchStateRepo: webSearchStateRepo,
|
||||
webSearchProviderRepo: webSearchProviderRepo,
|
||||
kbShareService: kbShareService,
|
||||
memoryService: memoryService,
|
||||
suggestionRepo: suggestionRepo,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,11 +27,10 @@ func (s *sessionService) KnowledgeQA(
|
||||
) error {
|
||||
logger.Infof(
|
||||
ctx,
|
||||
"Knowledge base question answering parameters, session ID: %s, query: %s, webSearchEnabled: %v, enableMemory: %v",
|
||||
"Knowledge base question answering parameters, session ID: %s, query: %s, webSearchEnabled: %v",
|
||||
req.Session.ID,
|
||||
req.Query,
|
||||
req.WebSearchEnabled,
|
||||
req.EnableMemory,
|
||||
)
|
||||
|
||||
// Span the request setup (KB / model resolution, search target building,
|
||||
@@ -103,15 +102,11 @@ func (s *sessionService) KnowledgeQA(
|
||||
len(searchTargets),
|
||||
)
|
||||
|
||||
// Scope memory and pipeline attribution to the same owner as the session.
|
||||
userID := types.SessionOwnerIDFromContext(ctx)
|
||||
|
||||
chatManage := &types.ChatManage{
|
||||
PipelineRequest: types.PipelineRequest{
|
||||
Query: req.Query,
|
||||
SessionID: req.Session.ID,
|
||||
UserID: userID,
|
||||
EnableMemory: req.EnableMemory,
|
||||
UserID: types.SessionOwnerIDFromContext(ctx),
|
||||
MaxRounds: s.cfg.Conversation.MaxRounds,
|
||||
KnowledgeBaseIDs: knowledgeBaseIDs,
|
||||
KnowledgeIDs: knowledgeIDs,
|
||||
@@ -184,9 +179,7 @@ func (s *sessionService) KnowledgeQA(
|
||||
|
||||
pipeline = types.NewPipelineBuilder().
|
||||
AddIf(hasHistory, types.LOAD_HISTORY).
|
||||
AddIf(chatManage.EnableMemory, types.MEMORY_RETRIEVAL).
|
||||
Add(types.CHAT_COMPLETION_STREAM).
|
||||
AddIf(chatManage.EnableMemory, types.MEMORY_STORAGE).
|
||||
Build()
|
||||
} else {
|
||||
// RAG — dynamically assemble based on feature flags.
|
||||
|
||||
@@ -585,7 +585,7 @@ func (s *userService) RevokeSystemAdmin(ctx context.Context, userID, actorID str
|
||||
// UpdateUserPreferences applies a partial update over the user's
|
||||
// preferences blob. PATCH semantics: only keys present in `patch`
|
||||
// (non-nil pointer fields) replace the existing value; everything else
|
||||
// is preserved. This lets the front-end PUT only the toggle that
|
||||
// is preserved. This lets the front-end PUT only the preference that
|
||||
// changed without having to read-modify-write the whole struct, and
|
||||
// also makes the endpoint forward-compatible — older clients that
|
||||
// don't know about newer keys won't accidentally erase them.
|
||||
@@ -600,10 +600,6 @@ func (s *userService) UpdateUserPreferences(
|
||||
}
|
||||
|
||||
merged := user.Preferences
|
||||
if patch.EnableMemory != nil {
|
||||
v := *patch.EnableMemory
|
||||
merged.EnableMemory = &v
|
||||
}
|
||||
if patch.LastActiveTenantID != nil {
|
||||
// *0 = "forget my preference, fall back to home on next login";
|
||||
// any positive value = set/replace. We do not validate membership
|
||||
|
||||
Reference in New Issue
Block a user