Skip to content

Commit 36b1a5e

Browse files
committed
Fix conversation memory duplication bug
- Move user message addition from before to after LLM processing - Prevents duplicate messages in conversation history - Ensures chat_history only contains previous messages, not current
1 parent 1d88326 commit 36b1a5e

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed

src/agents/mcp_agent.ts

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -483,11 +483,7 @@ export class MCPAgent {
483483
= query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, ' ')}...` : query.replace(/\n/g, ' ')
484484
logger.info(`💬 Received query: '${display_query}'`)
485485

486-
// —–– Record user message
487-
if (this.memoryEnabled) {
488-
this.addToHistory(new HumanMessage(query))
489-
}
490-
486+
// Prepare history (WITHOUT adding current message yet)
491487
const historyToUse = externalHistory ?? this.conversationHistory
492488
const langchainHistory: BaseMessage[] = []
493489
for (const msg of historyToUse) {
@@ -669,6 +665,14 @@ export class MCPAgent {
669665
logger.info('🎉 Agent execution complete')
670666
success = true
671667

668+
// Add BOTH the user message and AI response to conversation history if memory is enabled
669+
if (this.memoryEnabled) {
670+
this.addToHistory(new HumanMessage(query))
671+
if (result) {
672+
this.addToHistory(new AIMessage(result as string))
673+
}
674+
}
675+
672676
// Return regular result
673677
return result as string | T
674678
}
@@ -802,13 +806,7 @@ export class MCPAgent {
802806
= query.length > 50 ? `${query.slice(0, 50).replace(/\n/g, ' ')}...` : query.replace(/\n/g, ' ')
803807
logger.info(`💬 Received query for streamEvents: '${display_query}'`)
804808

805-
// Add user message to history if memory enabled
806-
if (this.memoryEnabled) {
807-
logger.info(`🔄 Adding user message to history: ${query}`)
808-
this.addToHistory(new HumanMessage(query))
809-
}
810-
811-
// Prepare history
809+
// Prepare history (WITHOUT adding current message yet)
812810
const historyToUse = externalHistory ?? this.conversationHistory
813811
const langchainHistory: BaseMessage[] = []
814812
for (const msg of historyToUse) {
@@ -859,9 +857,12 @@ export class MCPAgent {
859857
}
860858
}
861859

862-
// Add the final AI response to conversation history if memory is enabled
863-
if (this.memoryEnabled && finalResponse) {
864-
this.addToHistory(new AIMessage(finalResponse))
860+
// Add BOTH the user message and AI response to conversation history if memory is enabled
861+
if (this.memoryEnabled) {
862+
this.addToHistory(new HumanMessage(query))
863+
if (finalResponse) {
864+
this.addToHistory(new AIMessage(finalResponse))
865+
}
865866
}
866867

867868
logger.info(`🎉 StreamEvents complete - ${eventCount} events emitted`)

0 commit comments

Comments
 (0)