-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0168ae7
commit 1423476
Showing
2 changed files
with
107 additions
and
99 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import { BaseListChatMessageHistory } from "@langchain/core/chat_history"; | ||
import { | ||
BaseMessage, | ||
mapChatMessagesToStoredMessages, | ||
mapStoredMessagesToChatMessages, | ||
HumanMessage, | ||
AIMessage, | ||
} from "@langchain/core/messages"; | ||
|
||
class CustomChatMessageHistory extends BaseListChatMessageHistory { | ||
constructor(sessionId) { | ||
super(); | ||
this.sessionId = sessionId; | ||
this.fakeDatabase = {}; // Simulate a real database layer. Stores serialized objects. | ||
} | ||
|
||
async getMessages() { | ||
const messages = this.fakeDatabase[this.sessionId] || []; | ||
return mapStoredMessagesToChatMessages(messages); | ||
} | ||
|
||
async addMessage(message) { | ||
if (!this.fakeDatabase[this.sessionId]) { | ||
this.fakeDatabase[this.sessionId] = []; | ||
} | ||
const serializedMessages = mapChatMessagesToStoredMessages([message]); | ||
this.fakeDatabase[this.sessionId].push(serializedMessages[0]); | ||
} | ||
|
||
async addMessages(messages) { | ||
if (!this.fakeDatabase[this.sessionId]) { | ||
this.fakeDatabase[this.sessionId] = []; | ||
} | ||
const existingMessages = this.fakeDatabase[this.sessionId]; | ||
const serializedMessages = mapChatMessagesToStoredMessages(messages); | ||
this.fakeDatabase[this.sessionId] = existingMessages.concat(serializedMessages); | ||
} | ||
|
||
async clear() { | ||
delete this.fakeDatabase[this.sessionId]; | ||
} | ||
|
||
async loadMemoryVariables() { | ||
const messages = await this.getMessages(); | ||
return { | ||
history: messages, | ||
}; | ||
} | ||
|
||
async saveContext(inputs, outputs) { | ||
const userMessage = new HumanMessage({ | ||
content: inputs.input || '', | ||
}); | ||
const aiMessage = new AIMessage({ | ||
content: outputs.response || '', | ||
}); | ||
await this.addMessages([userMessage, aiMessage]); | ||
} | ||
} | ||
|
||
export default CustomChatMessageHistory; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters