-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
chat_memory.ts
70 lines (62 loc) · 2.08 KB
/
chat_memory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { BaseChatMessageHistory } from "@langchain/core/chat_history";
import {
BaseMemory,
InputValues,
OutputValues,
getInputValue,
getOutputValue,
} from "@langchain/core/memory";
import { ChatMessageHistory } from "../stores/message/in_memory.js";
/**
* Interface for the input parameters of the BaseChatMemory class.
*/
export interface BaseChatMemoryInput {
chatHistory?: BaseChatMessageHistory;
returnMessages?: boolean;
inputKey?: string;
outputKey?: string;
}
/**
* Abstract class that provides a base for implementing different types of
* memory systems. It is designed to maintain the state of an application,
* specifically the history of a conversation. This class is typically
* extended by other classes to create specific types of memory systems.
*/
export abstract class BaseChatMemory extends BaseMemory {
chatHistory: BaseChatMessageHistory;
returnMessages = false;
inputKey?: string;
outputKey?: string;
constructor(fields?: BaseChatMemoryInput) {
super();
this.chatHistory = fields?.chatHistory ?? new ChatMessageHistory();
this.returnMessages = fields?.returnMessages ?? this.returnMessages;
this.inputKey = fields?.inputKey ?? this.inputKey;
this.outputKey = fields?.outputKey ?? this.outputKey;
}
/**
* Method to add user and AI messages to the chat history in sequence.
* @param inputValues The input values from the user.
* @param outputValues The output values from the AI.
* @returns Promise that resolves when the context has been saved.
*/
async saveContext(
inputValues: InputValues,
outputValues: OutputValues
): Promise<void> {
// this is purposefully done in sequence so they're saved in order
await this.chatHistory.addUserMessage(
getInputValue(inputValues, this.inputKey)
);
await this.chatHistory.addAIChatMessage(
getOutputValue(outputValues, this.outputKey)
);
}
/**
* Method to clear the chat history.
* @returns Promise that resolves when the chat history has been cleared.
*/
async clear(): Promise<void> {
await this.chatHistory.clear();
}
}