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
+9 -9
View File
@@ -18,14 +18,19 @@ import (
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// langfuseQueryPreview caps the query length we ship as the agent.execute
// span input — long quoted-context queries can be many KB of prose.
const langfuseQueryPreview = 2000
// AgentEngine is the core engine for running ReAct agents
// AgentEngine is the core engine for running ReAct agents.
//
// History persistence note: the engine is stateless across turns. Conversation
// history is rebuilt from the DB once per turn by the caller
// (see service.LoadAgentHistory) and passed into Execute as llmContext. The
// engine therefore does not maintain its own cache, system-prompt store, or
// cross-turn buffer.
type AgentEngine struct {
config *types.AgentConfig
toolRegistry *agenttools.ToolRegistry
@@ -33,8 +38,7 @@ type AgentEngine struct {
eventBus *event.EventBus
knowledgeBasesInfo []*KnowledgeBaseInfo // Detailed knowledge base information for prompt
selectedDocs []*SelectedDocumentInfo // User-selected documents (via @ mention)
contextManager interfaces.ContextManager // Context manager for writing agent conversation to LLM context
sessionID string // Session ID for context management
sessionID string // Session ID for logging and event emission
systemPromptTemplate string // System prompt template (optional, uses default if empty)
skillsManager *skills.Manager // Skills manager for Progressive Disclosure (optional)
appConfig *appconfig.Config // Application config for prompt template resolution (optional)
@@ -57,7 +61,6 @@ func NewAgentEngine(
eventBus *event.EventBus,
knowledgeBasesInfo []*KnowledgeBaseInfo,
selectedDocs []*SelectedDocumentInfo,
contextManager interfaces.ContextManager,
sessionID string,
systemPromptTemplate string,
) *AgentEngine {
@@ -75,7 +78,6 @@ func NewAgentEngine(
eventBus: eventBus,
knowledgeBasesInfo: knowledgeBasesInfo,
selectedDocs: selectedDocs,
contextManager: contextManager,
sessionID: sessionID,
systemPromptTemplate: systemPromptTemplate,
tokenEstimator: tokenEst,
@@ -99,7 +101,6 @@ func NewAgentEngineWithSkills(
eventBus *event.EventBus,
knowledgeBasesInfo []*KnowledgeBaseInfo,
selectedDocs []*SelectedDocumentInfo,
contextManager interfaces.ContextManager,
sessionID string,
systemPromptTemplate string,
skillsManager *skills.Manager,
@@ -111,7 +112,6 @@ func NewAgentEngineWithSkills(
eventBus,
knowledgeBasesInfo,
selectedDocs,
contextManager,
sessionID,
systemPromptTemplate,
)
@@ -630,7 +630,7 @@ func (e *AgentEngine) runReActIteration(
// 4. Observe: Add tool results to messages and write to context
state.RoundSteps = append(state.RoundSteps, step)
*messagesPtr = e.appendToolResults(ctx, *messagesPtr, step)
*messagesPtr = e.appendToolResults(*messagesPtr, step)
common.PipelineInfo(ctx, "Agent", "round_end", map[string]interface{}{
"iteration": state.CurrentRound,
"round": round,
-1
View File
@@ -79,7 +79,6 @@ func newTestEngine(t *testing.T, chatModel chat.Chat, opts ...testEngineOption)
event.NewEventBus(),
nil,
nil,
nil,
"test-session",
"",
)
+4 -21
View File
@@ -368,10 +368,11 @@ func (e *AgentEngine) buildToolsForLLM() []chat.Tool {
return tools
}
// appendToolResults adds tool results to the message history following OpenAI's tool calling format
// Also writes these messages to the context manager for persistence
// appendToolResults adds tool results to the in-turn message history following
// OpenAI's tool-calling format. Cross-turn persistence is handled separately:
// the final AgentSteps are written to the assistant message by the SSE handler,
// and rebuilt from DB on the next turn by service.LoadAgentHistory.
func (e *AgentEngine) appendToolResults(
ctx context.Context,
messages []chat.Message,
step types.AgentStep,
) []chat.Message {
@@ -401,15 +402,6 @@ func (e *AgentEngine) appendToolResults(
}
messages = append(messages, assistantMsg)
// Write assistant message to context
if e.contextManager != nil {
if err := e.contextManager.AddMessage(ctx, e.sessionID, assistantMsg); err != nil {
logger.Warnf(ctx, "[Agent] Failed to add assistant message to context: %v", err)
} else {
logger.Debugf(ctx, "[Agent] Added assistant message to context (session: %s)", e.sessionID)
}
}
}
// Add tool result messages (role: "tool", following OpenAI format)
@@ -427,15 +419,6 @@ func (e *AgentEngine) appendToolResults(
}
messages = append(messages, toolMsg)
// Write tool message to context
if e.contextManager != nil {
if err := e.contextManager.AddMessage(ctx, e.sessionID, toolMsg); err != nil {
logger.Warnf(ctx, "[Agent] Failed to add tool message to context: %v", err)
} else {
logger.Debugf(ctx, "[Agent] Added tool message to context (session: %s, tool: %s)", e.sessionID, toolCall.Name)
}
}
}
return messages