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
|
||||
|
||||
@@ -35,7 +35,6 @@ import (
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/approval"
|
||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||
memoryRepo "github.com/Tencent/WeKnora/internal/application/repository/memory/neo4j"
|
||||
dorisRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/doris"
|
||||
elasticsearchRepoV7 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v7"
|
||||
elasticsearchRepoV8 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v8"
|
||||
@@ -50,7 +49,6 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
|
||||
"github.com/Tencent/WeKnora/internal/application/service/file"
|
||||
memoryService "github.com/Tencent/WeKnora/internal/application/service/memory"
|
||||
"github.com/Tencent/WeKnora/internal/application/service/retriever"
|
||||
"github.com/Tencent/WeKnora/internal/common"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
@@ -157,7 +155,6 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(repository.NewAuthTokenRepository))
|
||||
must(container.Provide(repository.NewSystemSettingRepository))
|
||||
must(container.Provide(neo4jRepo.NewNeo4jRepository))
|
||||
must(container.Provide(memoryRepo.NewMemoryRepository))
|
||||
must(container.Provide(repository.NewMCPServiceRepository))
|
||||
must(container.Provide(repository.NewMCPToolApprovalRepository))
|
||||
must(container.Provide(repository.NewMCPOAuthRepository))
|
||||
@@ -217,7 +214,6 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Provide(service.NewMCPToolApprovalService))
|
||||
must(container.Provide(service.NewCustomAgentService))
|
||||
must(container.Provide(service.NewUserResourceFavoriteService))
|
||||
must(container.Provide(memoryService.NewMemoryService))
|
||||
must(container.Provide(service.NewWikiPageService))
|
||||
must(container.Provide(service.NewWikiLogEntryService))
|
||||
must(container.Provide(service.NewWikiIngestService, dig.Name("wikiIngest")))
|
||||
@@ -337,7 +333,6 @@ func BuildContainer(container *dig.Container) *dig.Container {
|
||||
must(container.Invoke(chatpipeline.NewPluginSearchEntity))
|
||||
must(container.Invoke(chatpipeline.NewPluginSearchParallel))
|
||||
must(container.Invoke(chatpipeline.NewPluginWikiBoost))
|
||||
must(container.Invoke(chatpipeline.NewMemoryPlugin))
|
||||
logger.Debugf(ctx, "[Container] Chat pipeline plugins registered")
|
||||
|
||||
// HTTP handlers layer
|
||||
|
||||
@@ -583,7 +583,6 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
|
||||
// (preserve existing value) from "explicit false". See
|
||||
// types.UserPreferences for the persistence-layer counterpart.
|
||||
type updateMyPreferencesRequest struct {
|
||||
EnableMemory *bool `json:"enable_memory"`
|
||||
// LastActiveTenantID lets the SPA persist "after a fresh login,
|
||||
// drop me back into this workspace" across devices. Send a positive
|
||||
// workspace id to set / replace, or 0 to clear. Membership is validated
|
||||
@@ -623,7 +622,6 @@ func (h *AuthHandler) UpdateMyPreferences(c *gin.Context) {
|
||||
}
|
||||
|
||||
patch := types.UserPreferences{
|
||||
EnableMemory: req.EnableMemory,
|
||||
LastActiveTenantID: req.LastActiveTenantID,
|
||||
}
|
||||
prefs, err := h.userService.UpdateUserPreferences(ctx, user.ID, patch)
|
||||
|
||||
@@ -71,7 +71,6 @@ type embedChannelRequest struct {
|
||||
ShowSuggestedQuestions *bool `json:"show_suggested_questions"`
|
||||
WidgetPosition string `json:"widget_position"`
|
||||
AllowWebSearch *bool `json:"allow_web_search"`
|
||||
AllowMemory *bool `json:"allow_memory"`
|
||||
AllowFileUpload *bool `json:"allow_file_upload"`
|
||||
DefaultLocale *string `json:"default_locale"`
|
||||
WebhookURL *string `json:"webhook_url"`
|
||||
@@ -152,10 +151,6 @@ func (h *EmbedChannelHandler) CreateEmbedChannel(c *gin.Context) {
|
||||
if req.AllowWebSearch != nil {
|
||||
allowWebSearch = *req.AllowWebSearch
|
||||
}
|
||||
allowMemory := false
|
||||
if req.AllowMemory != nil {
|
||||
allowMemory = *req.AllowMemory
|
||||
}
|
||||
allowFileUpload := false
|
||||
if req.AllowFileUpload != nil {
|
||||
allowFileUpload = *req.AllowFileUpload
|
||||
@@ -173,7 +168,6 @@ func (h *EmbedChannelHandler) CreateEmbedChannel(c *gin.Context) {
|
||||
ShowSuggestedQuestions: showSuggested,
|
||||
WidgetPosition: req.WidgetPosition,
|
||||
AllowWebSearch: allowWebSearch,
|
||||
AllowMemory: allowMemory,
|
||||
AllowFileUpload: allowFileUpload,
|
||||
DefaultLocale: types.NormalizeEmbedDefaultLocale(stringOrEmpty(req.DefaultLocale)),
|
||||
})
|
||||
@@ -255,7 +249,7 @@ func (h *EmbedChannelHandler) UpdateEmbedChannel(c *gin.Context) {
|
||||
if req.AgentID != nil {
|
||||
update.AgentID = strings.TrimSpace(*req.AgentID)
|
||||
}
|
||||
ch, err := h.embedSvc.Update(c.Request.Context(), tenantID, channelID, update, req.Enabled, req.ShowSuggestedQuestions, req.AllowWebSearch, req.AllowMemory, req.AllowFileUpload, req.DefaultLocale, req.WebhookURL, req.WebhookSecret)
|
||||
ch, err := h.embedSvc.Update(c.Request.Context(), tenantID, channelID, update, req.Enabled, req.ShowSuggestedQuestions, req.AllowWebSearch, req.AllowFileUpload, req.DefaultLocale, req.WebhookURL, req.WebhookSecret)
|
||||
if err != nil {
|
||||
writeEmbedMgmtError(c, err)
|
||||
return
|
||||
@@ -710,8 +704,6 @@ func patchEmbedChatPayload(body io.Reader, ch *types.EmbedChannel, agentMode boo
|
||||
}
|
||||
// Channel allow_web_search only exposes the visitor toggle; the client must opt in.
|
||||
payload["web_search_enabled"] = ch.AllowWebSearch && clientWebSearch
|
||||
// Embed memory UI is disabled for now; always off regardless of channel flag.
|
||||
payload["enable_memory"] = false
|
||||
if !ch.AllowFileUpload {
|
||||
delete(payload, "images")
|
||||
delete(payload, "attachment_uploads")
|
||||
@@ -796,7 +788,6 @@ func embedChannelResponse(ch *types.EmbedChannel, publishToken string) gin.H {
|
||||
"show_suggested_questions": ch.ShowSuggestedQuestions,
|
||||
"widget_position": ch.WidgetPosition,
|
||||
"allow_web_search": ch.AllowWebSearch,
|
||||
"allow_memory": ch.AllowMemory,
|
||||
"allow_file_upload": ch.AllowFileUpload,
|
||||
"default_locale": ch.DefaultLocale,
|
||||
"webhook_url": ch.WebhookURL,
|
||||
|
||||
@@ -28,7 +28,7 @@ func (f *exchangeEmbedSvc) ListByAgent(context.Context, uint64, string) ([]*type
|
||||
func (f *exchangeEmbedSvc) ListByTenant(context.Context, uint64) ([]*types.EmbedChannel, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *exchangeEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
|
||||
func (f *exchangeEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *exchangeEmbedSvc) GetOwnedChannel(context.Context, uint64, string) (*types.EmbedChannel, error) {
|
||||
|
||||
@@ -32,7 +32,7 @@ func (f *flowEmbedSvc) ListByAgent(context.Context, uint64, string) ([]*types.Em
|
||||
func (f *flowEmbedSvc) ListByTenant(context.Context, uint64) ([]*types.EmbedChannel, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *flowEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
|
||||
func (f *flowEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *flowEmbedSvc) GetOwnedChannel(_ context.Context, tenantID uint64, id string) (*types.EmbedChannel, error) {
|
||||
@@ -214,7 +214,7 @@ func TestPatchEmbedChatPayloadInjectsAgentID(t *testing.T) {
|
||||
|
||||
func TestPatchEmbedChatPayloadWebSearchRequiresClientOptIn(t *testing.T) {
|
||||
ch := &types.EmbedChannel{AgentID: "agent-1", AllowWebSearch: true}
|
||||
body := `{"query":"hello","web_search_enabled":false,"enable_memory":true}`
|
||||
body := `{"query":"hello","web_search_enabled":false}`
|
||||
|
||||
patched, err := patchEmbedChatPayload(strings.NewReader(body), ch, false)
|
||||
if err != nil {
|
||||
@@ -227,9 +227,6 @@ func TestPatchEmbedChatPayloadWebSearchRequiresClientOptIn(t *testing.T) {
|
||||
if payload["web_search_enabled"] != false {
|
||||
t.Fatalf("web_search_enabled = %v, want false when visitor did not opt in", payload["web_search_enabled"])
|
||||
}
|
||||
if payload["enable_memory"] != false {
|
||||
t.Fatalf("enable_memory = %v, want false (embed memory is disabled)", payload["enable_memory"])
|
||||
}
|
||||
|
||||
bodyOn := `{"query":"hello","web_search_enabled":true}`
|
||||
patchedOn, err := patchEmbedChatPayload(strings.NewReader(bodyOn), ch, false)
|
||||
|
||||
@@ -78,7 +78,7 @@ func (s *sessionEmbedSvc) ListByAgent(context.Context, uint64, string) ([]*types
|
||||
func (s *sessionEmbedSvc) ListByTenant(context.Context, uint64) ([]*types.EmbedChannel, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (s *sessionEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
|
||||
func (s *sessionEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (s *sessionEmbedSvc) GetOwnedChannel(context.Context, uint64, string) (*types.EmbedChannel, error) {
|
||||
|
||||
@@ -29,7 +29,6 @@ type Handler struct {
|
||||
fileService interfaces.FileService // Service for file storage (image uploads)
|
||||
storageResolver interfaces.StorageBackendResolver
|
||||
modelService interfaces.ModelService // Service for model management (VLM access)
|
||||
userService interfaces.UserService // Service for resolving per-user preferences (e.g. enable_memory default)
|
||||
attachmentProcessor *AttachmentProcessor // Processor for file attachments
|
||||
temporaryDocuments interfaces.TemporaryDocumentService
|
||||
}
|
||||
@@ -49,7 +48,6 @@ func NewHandler(
|
||||
fileService interfaces.FileService,
|
||||
storageResolver interfaces.StorageBackendResolver,
|
||||
modelService interfaces.ModelService,
|
||||
userService interfaces.UserService,
|
||||
documentReader interfaces.DocumentReader,
|
||||
imageResolver *docparser.ImageResolver,
|
||||
temporaryDocuments interfaces.TemporaryDocumentService,
|
||||
@@ -68,7 +66,6 @@ func NewHandler(
|
||||
fileService: fileService,
|
||||
storageResolver: storageResolver,
|
||||
modelService: modelService,
|
||||
userService: userService,
|
||||
temporaryDocuments: temporaryDocuments,
|
||||
attachmentProcessor: NewAttachmentProcessor(
|
||||
fileService,
|
||||
|
||||
@@ -41,7 +41,6 @@ type qaRequestContext struct {
|
||||
skillNames []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
|
||||
images []ImageAttachment // Uploaded images with analysis text
|
||||
@@ -77,7 +76,6 @@ func (rc *qaRequestContext) buildQARequest() *types.QARequest {
|
||||
ImageDescription: imageDescription,
|
||||
UserMessageID: rc.userMessageID,
|
||||
WebSearchEnabled: rc.webSearchEnabled,
|
||||
EnableMemory: rc.enableMemory,
|
||||
Attachments: rc.attachments,
|
||||
}
|
||||
}
|
||||
@@ -286,17 +284,6 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
||||
attachmentIDs = normalizedIDs
|
||||
}
|
||||
|
||||
// Resolve enable_memory:
|
||||
// 1. Explicit value in request → honour it. Used by embedded mode
|
||||
// (force false) and by older clients still sending the literal bool.
|
||||
// 2. Not set → fall back to the calling user's stored preference.
|
||||
// The toggle is persisted server-side per user (see PUT
|
||||
// /auth/me/preferences); this is the canonical path for the
|
||||
// normal logged-in web UI now that it no longer sends the field.
|
||||
// 3. No user / no preference → false. API-key-only callers never
|
||||
// had memory enabled in practice, keep that behaviour.
|
||||
enableMemory := h.resolveEnableMemory(ctx, request.EnableMemory)
|
||||
|
||||
mentionScopes := tagScopesFromMentionedItems(request.MentionedItems)
|
||||
requestTagIDs := dedupRequestStrings(request.TagIDs)
|
||||
if err := validateUnscopedTagIDs(orphanTagIDsForScope(requestTagIDs, mentionScopes), secutils.SanitizeForLogArray(kbIDs)); err != nil {
|
||||
@@ -349,7 +336,6 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
||||
skillNames: secutils.SanitizeForLogArray(skillNames),
|
||||
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
|
||||
webSearchEnabled: request.WebSearchEnabled,
|
||||
enableMemory: enableMemory,
|
||||
mentionedItems: convertMentionedItems(request.MentionedItems),
|
||||
effectiveTenantID: effectiveTenantID,
|
||||
images: request.Images,
|
||||
@@ -456,32 +442,6 @@ func cloneTagScopes(scopes []types.TagScope) []types.TagScope {
|
||||
return cloned
|
||||
}
|
||||
|
||||
// resolveEnableMemory decides whether the memory pipeline runs for this
|
||||
// request. See the call-site comment in parseQARequest for the resolution
|
||||
// order. Lookup errors are logged but never propagate — a failure to read
|
||||
// the user's preference shouldn't break the chat request itself, we just
|
||||
// fall back to false (the safe default).
|
||||
func (h *Handler) resolveEnableMemory(ctx context.Context, override *bool) bool {
|
||||
if override != nil {
|
||||
return *override
|
||||
}
|
||||
if h.userService == nil {
|
||||
return false
|
||||
}
|
||||
user, err := h.userService.GetCurrentUser(ctx)
|
||||
if err != nil {
|
||||
// API-key-only callers or revoked sessions land here; the chat
|
||||
// request itself stays authorised via the middleware that already
|
||||
// ran, we just have nobody to look preferences up for.
|
||||
logger.Debugf(ctx, "enable_memory: no user in context, defaulting to false: %v", err)
|
||||
return false
|
||||
}
|
||||
if user.Preferences.EnableMemory != nil {
|
||||
return *user.Preferences.EnableMemory
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// resolveAgent resolves the custom agent by ID, trying shared agent first, then own agent.
|
||||
// Returns (nil, 0) if agentID is empty or not found.
|
||||
func (h *Handler) resolveAgent(ctx context.Context, c *gin.Context, agentID string) (*types.CustomAgent, uint64) {
|
||||
|
||||
@@ -42,34 +42,22 @@ type ImageAttachment struct {
|
||||
|
||||
// CreateKnowledgeQARequest defines the request structure for knowledge QA
|
||||
type CreateKnowledgeQARequest struct {
|
||||
Query string `json:"query" binding:"required"` // Query text for knowledge base search
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request
|
||||
KnowledgeIds []string `json:"knowledge_ids"` // Selected knowledge ID for this request
|
||||
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
|
||||
AgentID string `json:"agent_id"` // Selected custom agent ID (backend resolves shared agent and its workspace from share relation)
|
||||
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
|
||||
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
|
||||
MCPServiceIDs []string `json:"mcp_service_ids"` // Per-request MCP services selected via @mention
|
||||
SkillNames []string `json:"skill_names"` // Per-request Skills selected via @mention
|
||||
TagIDs []string `json:"tag_ids"` // @mentioned tag IDs (display/debug; scoped via MentionedItems)
|
||||
MentionedItems []MentionedItemRequest `json:"mentioned_items"` // @mentioned knowledge bases and files
|
||||
DisableTitle bool `json:"disable_title"` // Whether to disable auto title generation
|
||||
// EnableMemory is the per-request override for the memory feature.
|
||||
// Pointer + omitempty so the request can distinguish three states:
|
||||
// nil = client did not specify; backend falls back to the calling
|
||||
// user's persisted preference (user.preferences.enable_memory),
|
||||
// defaulting to false if that's also unset. This is the path
|
||||
// used by the normal logged-in chat UI now that the toggle is
|
||||
// stored server-side per user.
|
||||
// *true / *false = explicit override. Embedded mode forces *false so a
|
||||
// user's personal memory setting doesn't leak into a widget
|
||||
// context; older clients that still send a literal bool also
|
||||
// land here (back-compat).
|
||||
EnableMemory *bool `json:"enable_memory,omitempty"`
|
||||
Images []ImageAttachment `json:"images"` // Attached images for multimodal chat
|
||||
AttachmentUploads []AttachmentUpload `json:"attachment_uploads,omitempty"` // Attached files (documents, audio, etc.)
|
||||
AttachmentIDs []string `json:"attachment_ids,omitempty"` // Pre-uploaded session-scoped document IDs
|
||||
Channel string `json:"channel"` // Source channel: "web", "api", "im", etc.
|
||||
Query string `json:"query" binding:"required"` // Query text for knowledge base search
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request
|
||||
KnowledgeIds []string `json:"knowledge_ids"` // Selected knowledge ID for this request
|
||||
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
|
||||
AgentID string `json:"agent_id"` // Selected custom agent ID (backend resolves shared agent and its workspace from share relation)
|
||||
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
|
||||
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
|
||||
MCPServiceIDs []string `json:"mcp_service_ids"` // Per-request MCP services selected via @mention
|
||||
SkillNames []string `json:"skill_names"` // Per-request Skills selected via @mention
|
||||
TagIDs []string `json:"tag_ids"` // @mentioned tag IDs (display/debug; scoped via MentionedItems)
|
||||
MentionedItems []MentionedItemRequest `json:"mentioned_items"` // @mentioned knowledge bases and files
|
||||
DisableTitle bool `json:"disable_title"` // Whether to disable auto title generation
|
||||
Images []ImageAttachment `json:"images"` // Attached images for multimodal chat
|
||||
AttachmentUploads []AttachmentUpload `json:"attachment_uploads,omitempty"` // Attached files (documents, audio, etc.)
|
||||
AttachmentIDs []string `json:"attachment_ids,omitempty"` // Pre-uploaded session-scoped document IDs
|
||||
Channel string `json:"channel"` // Source channel: "web", "api", "im", etc.
|
||||
SuggestionAttribution *types.SuggestionAttribution `json:"suggestion_attribution,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ func (f *fakeEmbedChannelService) ListByTenant(
|
||||
|
||||
func (f *fakeEmbedChannelService) 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) {
|
||||
return nil, nil
|
||||
|
||||
@@ -4,11 +4,10 @@ import "maps"
|
||||
|
||||
// PipelineRequest holds immutable configuration set once at the request entry point.
|
||||
type PipelineRequest struct {
|
||||
SessionID string `json:"session_id"`
|
||||
UserID string `json:"user_id"`
|
||||
Query string `json:"query,omitempty"`
|
||||
EnableMemory bool `json:"enable_memory"`
|
||||
MaxRounds int `json:"max_rounds"`
|
||||
SessionID string `json:"session_id"`
|
||||
UserID string `json:"user_id"`
|
||||
Query string `json:"query,omitempty"`
|
||||
MaxRounds int `json:"max_rounds"`
|
||||
|
||||
// Knowledge base retrieval parameters
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
|
||||
@@ -204,7 +203,6 @@ func (c *ChatManage) Clone() *ChatManage {
|
||||
Query: c.Query,
|
||||
SessionID: c.SessionID,
|
||||
UserID: c.UserID,
|
||||
EnableMemory: c.EnableMemory,
|
||||
MaxRounds: c.MaxRounds,
|
||||
KnowledgeBaseIDs: knowledgeBaseIDs,
|
||||
KnowledgeIDs: knowledgeIDs,
|
||||
@@ -275,8 +273,6 @@ const (
|
||||
CHAT_COMPLETION EventType = "chat_completion"
|
||||
CHAT_COMPLETION_STREAM EventType = "chat_completion_stream"
|
||||
FILTER_TOP_K EventType = "filter_top_k"
|
||||
MEMORY_RETRIEVAL EventType = "memory_retrieval"
|
||||
MEMORY_STORAGE EventType = "memory_storage"
|
||||
)
|
||||
|
||||
// PipelineBuilder dynamically assembles a pipeline as an ordered list of EventTypes.
|
||||
@@ -321,9 +317,7 @@ var Pipeline = map[string][]EventType{
|
||||
},
|
||||
"chat_history_stream": {
|
||||
LOAD_HISTORY,
|
||||
MEMORY_RETRIEVAL,
|
||||
CHAT_COMPLETION_STREAM,
|
||||
MEMORY_STORAGE,
|
||||
},
|
||||
"rag": {
|
||||
CHUNK_SEARCH,
|
||||
|
||||
@@ -27,7 +27,6 @@ type EmbedChannel struct {
|
||||
ShowSuggestedQuestions bool `json:"show_suggested_questions" gorm:"not null;default:true"`
|
||||
WidgetPosition string `json:"widget_position" gorm:"type:varchar(32);not null;default:'bottom-right'"`
|
||||
AllowWebSearch bool `json:"allow_web_search" gorm:"not null;default:false"`
|
||||
AllowMemory bool `json:"allow_memory" gorm:"not null;default:false"`
|
||||
AllowFileUpload bool `json:"allow_file_upload" gorm:"not null;default:false"`
|
||||
DefaultLocale string `json:"default_locale" gorm:"type:varchar(16);not null;default:''"`
|
||||
WebhookURL string `json:"webhook_url" gorm:"type:varchar(512);not null;default:''"`
|
||||
@@ -119,7 +118,6 @@ type EmbedChannelPublicConfig struct {
|
||||
AllowedOrigins []string `json:"allowed_origins,omitempty"`
|
||||
WidgetPosition string `json:"widget_position,omitempty"`
|
||||
AllowWebSearch bool `json:"allow_web_search"`
|
||||
AllowMemory bool `json:"allow_memory"`
|
||||
AllowFileUpload bool `json:"allow_file_upload"`
|
||||
// AgentWebSearchEnabled reflects whether the bound agent has web search configured.
|
||||
AgentWebSearchEnabled bool `json:"agent_web_search_enabled"`
|
||||
|
||||
@@ -22,7 +22,7 @@ type EmbedChannelService interface {
|
||||
Create(ctx context.Context, tenantID uint64, agentID string, req *types.EmbedChannel) (*types.EmbedChannel, string, error)
|
||||
ListByAgent(ctx context.Context, tenantID uint64, agentID string) ([]*types.EmbedChannel, error)
|
||||
ListByTenant(ctx context.Context, tenantID uint64) ([]*types.EmbedChannel, error)
|
||||
Update(ctx context.Context, tenantID uint64, id string, req *types.EmbedChannel, enabled *bool, showSuggested *bool, allowWebSearch *bool, allowMemory *bool, allowFileUpload *bool, defaultLocale *string, webhookURL *string, webhookSecret *string) (*types.EmbedChannel, error)
|
||||
Update(ctx context.Context, tenantID uint64, id string, req *types.EmbedChannel, enabled *bool, showSuggested *bool, allowWebSearch *bool, allowFileUpload *bool, defaultLocale *string, webhookURL *string, webhookSecret *string) (*types.EmbedChannel, error)
|
||||
Delete(ctx context.Context, tenantID uint64, id string) error
|
||||
RotateToken(ctx context.Context, tenantID uint64, id string) (*types.EmbedChannel, string, error)
|
||||
LookupForEmbed(ctx context.Context, channelID, token string) (*types.EmbedChannel, error)
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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"`
|
||||
}
|
||||
@@ -18,7 +18,6 @@ type QARequest struct {
|
||||
ImageDescription string // VLM-generated image description (fallback for non-vision models)
|
||||
UserMessageID string // Created user message ID
|
||||
WebSearchEnabled bool // Whether web search is enabled for this request
|
||||
EnableMemory bool // Whether memory feature is enabled
|
||||
QuotedContext string // Quoted message content from IM quote-reply (appended at LLM prompt stage, not used for retrieval)
|
||||
Attachments MessageAttachments // File attachments (processed and ready for prompt injection)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// UserPreferences holds per-user UI/feature preferences persisted server-side
|
||||
// UserPreferences holds per-user preferences persisted server-side
|
||||
// so they sync across devices/browsers. Fields are pointers so we can
|
||||
// distinguish "client didn't send this key" (leave existing value alone)
|
||||
// from "client explicitly set false" — the partial-update merge in
|
||||
@@ -22,11 +22,6 @@ import (
|
||||
//
|
||||
// No DB DDL is required — preferences is a single jsonb column.
|
||||
type UserPreferences struct {
|
||||
// EnableMemory mirrors the "开启记忆功能" switch in General Settings.
|
||||
// nil = preference never set (treat as feature default = false)
|
||||
// *false / *true = user explicitly set the toggle.
|
||||
EnableMemory *bool `json:"enable_memory,omitempty"`
|
||||
|
||||
// LastActiveTenantID remembers the last workspace the user actively
|
||||
// switched into, so a fresh login (new device, cleared browser, new
|
||||
// refresh token) lands them back in that workspace instead of always
|
||||
@@ -95,7 +90,7 @@ type User struct {
|
||||
CanAccessAllTenants bool `json:"can_access_all_tenants" gorm:"default:false"`
|
||||
// Whether the user is a system administrator (independent of workspace roles)
|
||||
IsSystemAdmin bool `json:"is_system_admin" gorm:"default:false;index"`
|
||||
// Per-user UI/feature preferences (memory toggle, future knobs).
|
||||
// Per-user UI/feature preferences.
|
||||
// Stored as JSON (jsonb on Postgres, TEXT on SQLite) via the
|
||||
// driver.Valuer / sql.Scanner methods on UserPreferences.
|
||||
Preferences UserPreferences `json:"preferences" gorm:"type:jsonb;not null;default:'{}'"`
|
||||
|
||||
Reference in New Issue
Block a user