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
@@ -102,14 +102,15 @@ func NewAgentService(
}
}
// CreateAgentEngineWithEventBus creates an agent engine with the given configuration and EventBus
// CreateAgentEngine creates an agent engine with the given configuration and EventBus.
// History is loaded once per turn by the caller (see service.LoadAgentHistory)
// and handed to AgentEngine.Execute as llmContext; the engine is stateless across turns.
func (s *agentService) CreateAgentEngine(
ctx context.Context,
config *types.AgentConfig,
chatModel chat.Chat,
rerankModel rerank.Reranker,
eventBus *event.EventBus,
contextManager interfaces.ContextManager,
sessionID string,
) (interfaces.AgentEngine, error) {
logger.Infof(ctx, "Creating agent engine with custom EventBus")
@@ -144,7 +145,7 @@ func (s *agentService) CreateAgentEngine(
// 5. Create engine
engine := agent.NewAgentEngine(
config, chatModel, toolRegistry, eventBus,
kbInfos, selectedDocs, contextManager, sessionID,
kbInfos, selectedDocs, sessionID,
systemPromptTemplate,
)
engine.SetAppConfig(s.cfg)