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
+4 -5
View File
@@ -1230,16 +1230,15 @@ func (s *Service) handleCommand(
// Handle service-level side effects.
switch result.Action {
case ActionClear:
// Soft-delete the current ChannelSession and clear the LLM context
// so the next message creates a completely fresh conversation.
// Soft-delete the current ChannelSession so the next IM message
// starts a completely fresh WeKnora session. Conversation history
// is keyed by session ID and rebuilt from DB on demand, so no
// separate cache invalidation step is needed.
if err := s.db.Model(&ChannelSession{}).
Where("id = ?", channelSession.ID).
Update("deleted_at", time.Now()).Error; err != nil {
logger.Warnf(ctx, "[IM] Failed to soft-delete channel session: %v", err)
}
if err := s.sessionService.ClearContext(ctx, channelSession.SessionID); err != nil {
logger.Warnf(ctx, "[IM] Failed to clear session context: %v", err)
}
case ActionStop:
stopThreadID := ""
if channel.SessionMode == string(SessionModeThread) {