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
View File
@@ -374,10 +374,6 @@ func (h *Handler) ClearSessionMessages(c *gin.Context) {
return
}
if err := h.sessionService.ClearContext(ctx, id); err != nil {
logger.Warnf(ctx, "Failed to clear LLM context for session %s: %v", id, err)
}
logger.Infof(ctx, "Session messages cleared successfully, ID: %s", id)
c.JSON(http.StatusOK, gin.H{
"success": true,