refactor(agent): rebuild multi-turn history from DB, drop llmcontext layer

The Agent ran a parallel context cache (Redis/in-memory) on top of the
messages table to feed multi-turn history into the LLM. That dual-write
caused subtle drift (e.g. compression diverging from DB, system-prompt
swaps lost on restart) and required a separate ClearContext path on
session/IM clear.

Make the messages table the single source of truth:

- Add service.LoadAgentHistory: rebuilds chat.Message history per turn
  from the persisted messages, expanding AgentSteps into proper OpenAI
  assistant_with_tool_calls + tool messages and replaying the canonical
  final answer (with <think> blocks stripped). final_answer tool calls
  are filtered to avoid duplicating the trailing answer.
- Make AgentEngine stateless across turns: drop ContextManager / sessionID
  cache plumbing from the engine, agent service, and CreateAgentEngine
  signature. The engine only uses sessionID for logging/event emission.
- Wire AgentQA to load history from DB on demand using HistoryTurns
  (default 5) when MultiTurnEnabled, otherwise run with empty history.
- Delete the llmcontext package (ContextManager interface, Redis/memory
  storage, factory) and the SessionService.ClearContext API path; IM
  /clear and session message clear no longer need to invalidate cache.

Behavior preserved: KnowledgeQA-mode replay is unchanged (turns with
empty AgentSteps just produce the single canonical assistant message),
and Agent-mode turns now consistently see prior tool calls and results.
This commit is contained in:
wizardchen
2026-05-12 11:43:35 +08:00
committed by lyingbug
parent 0b2de5c412
commit 1f5970b67e
19 changed files with 466 additions and 621 deletions
@@ -8,13 +8,11 @@ import (
"os"
"github.com/Tencent/WeKnora/internal/agent/tools"
llmcontext "github.com/Tencent/WeKnora/internal/application/service/llmcontext"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// AgentQA performs agent-based question answering with conversation history and streaming support
@@ -117,38 +115,29 @@ func (s *sessionService) AgentQA(
logger.Infof(ctx, "knowledge_search tool not enabled, skipping rerank model initialization")
}
// Get or create contextManager for this session
contextManager := s.getContextManagerForSession()
// Set system prompt for the current agent in context manager
// This ensures the context uses the correct system prompt when switching agents
systemPrompt := agentConfig.ResolveSystemPrompt(agentConfig.WebSearchEnabled)
if systemPrompt != "" {
if err := contextManager.SetSystemPrompt(ctx, sessionID, systemPrompt); err != nil {
logger.Warnf(ctx, "Failed to set system prompt in context manager: %v", err)
} else {
logger.Infof(ctx, "System prompt updated in context manager for agent")
// Load multi-turn history directly from DB (the single source of truth).
// AgentSteps on each historical assistant message are expanded into proper
// assistant_with_tool_calls + tool messages so the model can see what was
// tried last turn — except final_answer, which is replayed as the trailing
// canonical assistant message.
var llmContext []chat.Message
if agentConfig.MultiTurnEnabled {
historyTurns := agentConfig.HistoryTurns
if historyTurns <= 0 {
historyTurns = 5
}
}
// Get LLM context from context manager
llmContext, err := s.getContextForSession(ctx, contextManager, sessionID)
if err != nil {
logger.Warnf(ctx, "Failed to get LLM context: %v, continuing without history", err)
llmContext = []chat.Message{}
}
logger.Infof(ctx, "Loaded %d messages from LLM context manager", len(llmContext))
// Apply multi-turn configuration for Agent mode
// Note: In Agent mode, context is managed by contextManager with compression strategies,
// so we don't apply HistoryTurns limit here. HistoryTurns is used in normal (KnowledgeQA) mode.
if !agentConfig.MultiTurnEnabled {
// Multi-turn disabled, clear history
logger.Infof(ctx, "Multi-turn disabled for this agent, clearing history context")
llmContext, err = LoadAgentHistory(ctx, s.messageRepo, sessionID, historyTurns)
if err != nil {
logger.Warnf(ctx, "Failed to load agent history from DB: %v, continuing without history", err)
llmContext = []chat.Message{}
}
logger.Infof(ctx, "Loaded %d history messages from DB (turns=%d)", len(llmContext), historyTurns)
} else {
logger.Infof(ctx, "Multi-turn disabled for this agent, running without history")
llmContext = []chat.Message{}
}
// Create agent engine with EventBus and ContextManager
// Create agent engine with EventBus
logger.Info(ctx, "Creating agent engine")
engine, err := s.agentService.CreateAgentEngine(
ctx,
@@ -156,7 +145,6 @@ func (s *sessionService) AgentQA(
summaryModel,
rerankModel,
eventBus,
contextManager,
sessionID,
)
if err != nil {
@@ -357,29 +345,3 @@ func (s *sessionService) configureSkillsFromAgent(
}
}
// getContextManagerForSession creates a context manager for the session.
func (s *sessionService) getContextManagerForSession() interfaces.ContextManager {
return llmcontext.NewContextManagerFromConfig(s.sessionStorage, s.messageRepo)
}
// getContextForSession retrieves LLM context for a session
func (s *sessionService) getContextForSession(
ctx context.Context,
contextManager interfaces.ContextManager,
sessionID string,
) ([]chat.Message, error) {
history, err := contextManager.GetContext(ctx, sessionID)
if err != nil {
return nil, fmt.Errorf("failed to get context: %w", err)
}
// Log context statistics
stats, _ := contextManager.GetContextStats(ctx, sessionID)
if stats != nil {
logger.Infof(ctx, "LLM context stats for session %s: messages=%d, tokens=~%d, compressed=%v",
sessionID, stats.MessageCount, stats.TokenCount, stats.IsCompressed)
}
return history, nil
}