UNPKG

@langchain/community

Version:
1 lines 8.28 kB
{"version":3,"file":"momento.cjs","names":["BaseListChatMessageHistory","CollectionTtl","ensureCacheExists","InvalidArgumentError","CacheListFetch","CacheListPushBack","CacheDelete"],"sources":["../../../src/stores/message/momento.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport {\n CacheDelete,\n CacheListFetch,\n CacheListPushBack,\n ICacheClient,\n InvalidArgumentError,\n CollectionTtl,\n} from \"@gomomento/sdk-core\";\nimport { BaseListChatMessageHistory } from \"@langchain/core/chat_history\";\nimport {\n BaseMessage,\n StoredMessage,\n mapChatMessagesToStoredMessages,\n mapStoredMessagesToChatMessages,\n} from \"@langchain/core/messages\";\nimport { ensureCacheExists } from \"../../utils/momento.js\";\n\n/**\n * The settings to instantiate the Momento chat message history.\n */\nexport interface MomentoChatMessageHistoryProps {\n /**\n * The session ID to use to store the data.\n */\n sessionId: string;\n /**\n * The Momento cache client.\n */\n client: ICacheClient;\n /**\n * The name of the cache to use to store the data.\n */\n cacheName: string;\n /**\n * The time to live for the cache items in seconds.\n * If not specified, the cache client default is used.\n */\n sessionTtl?: number;\n /**\n * If true, ensure that the cache exists before returning.\n * If false, the cache is not checked for existence.\n * Defaults to true.\n */\n ensureCacheExists?: true;\n}\n\n/**\n * A class that stores chat message history using Momento Cache. It\n * interacts with a Momento cache client to perform operations like\n * fetching, adding, and deleting messages.\n * @example\n * ```typescript\n * const chatHistory = await MomentoChatMessageHistory.fromProps({\n * client: new CacheClient({\n * configuration: Configurations.Laptop.v1(),\n * credentialProvider: CredentialProvider.fromEnvironmentVariable({\n * environmentVariableName: \"MOMENTO_API_KEY\",\n * }),\n * defaultTtlSeconds: 60 * 60 * 24,\n * }),\n * cacheName: \"langchain\",\n * sessionId: new Date().toISOString(),\n * sessionTtl: 300,\n * });\n *\n * const messages = await chatHistory.getMessages();\n * console.log({ messages });\n * ```\n */\nexport class MomentoChatMessageHistory extends BaseListChatMessageHistory {\n lc_namespace = [\"langchain\", \"stores\", \"message\", \"momento\"];\n\n private readonly sessionId: string;\n\n private readonly client: ICacheClient;\n\n private readonly cacheName: string;\n\n private readonly sessionTtl: CollectionTtl;\n\n private constructor(props: MomentoChatMessageHistoryProps) {\n super();\n this.sessionId = props.sessionId;\n this.client = props.client;\n this.cacheName = props.cacheName;\n\n this.validateTtlSeconds(props.sessionTtl);\n this.sessionTtl =\n props.sessionTtl !== undefined\n ? CollectionTtl.of(props.sessionTtl)\n : CollectionTtl.fromCacheTtl();\n }\n\n /**\n * Create a new chat message history backed by Momento.\n *\n * @param {MomentoCacheProps} props The settings to instantiate the Momento chat message history.\n * @param {string} props.sessionId The session ID to use to store the data.\n * @param {ICacheClient} props.client The Momento cache client.\n * @param {string} props.cacheName The name of the cache to use to store the data.\n * @param {number} props.sessionTtl The time to live for the cache items in seconds.\n * If not specified, the cache client default is used.\n * @param {boolean} props.ensureCacheExists If true, ensure that the cache exists before returning.\n * If false, the cache is not checked for existence.\n * @throws {InvalidArgumentError} If {@link props.sessionTtl} is not strictly positive.\n * @returns A new chat message history backed by Momento.\n */\n public static async fromProps(\n props: MomentoChatMessageHistoryProps\n ): Promise<MomentoChatMessageHistory> {\n const instance = new MomentoChatMessageHistory(props);\n if (props.ensureCacheExists || props.ensureCacheExists === undefined) {\n await ensureCacheExists(props.client, props.cacheName);\n }\n return instance;\n }\n\n /**\n * Validate the user-specified TTL, if provided, is strictly positive.\n * @param ttlSeconds The TTL to validate.\n */\n private validateTtlSeconds(ttlSeconds?: number): void {\n if (ttlSeconds !== undefined && ttlSeconds <= 0) {\n throw new InvalidArgumentError(\"ttlSeconds must be positive.\");\n }\n }\n\n /**\n * Fetches messages from the cache.\n * @returns A Promise that resolves to an array of BaseMessage instances.\n */\n public async getMessages(): Promise<BaseMessage[]> {\n const fetchResponse = await this.client.listFetch(\n this.cacheName,\n this.sessionId\n );\n\n let messages: StoredMessage[] = [];\n if (fetchResponse instanceof CacheListFetch.Hit) {\n messages = fetchResponse\n .valueList()\n .map((serializedStoredMessage) => JSON.parse(serializedStoredMessage));\n } else if (fetchResponse instanceof CacheListFetch.Miss) {\n // pass\n } else if (fetchResponse instanceof CacheListFetch.Error) {\n throw fetchResponse.innerException();\n } else {\n throw new Error(`Unknown response type: ${fetchResponse.toString()}`);\n }\n return mapStoredMessagesToChatMessages(messages);\n }\n\n /**\n * Adds a message to the cache.\n * @param message The BaseMessage instance to add to the cache.\n * @returns A Promise that resolves when the message has been added.\n */\n public async addMessage(message: BaseMessage): Promise<void> {\n const messageToAdd = JSON.stringify(\n mapChatMessagesToStoredMessages([message])[0]\n );\n\n const pushResponse = await this.client.listPushBack(\n this.cacheName,\n this.sessionId,\n messageToAdd,\n { ttl: this.sessionTtl }\n );\n if (pushResponse instanceof CacheListPushBack.Success) {\n // pass\n } else if (pushResponse instanceof CacheListPushBack.Error) {\n throw pushResponse.innerException();\n } else {\n throw new Error(`Unknown response type: ${pushResponse.toString()}`);\n }\n }\n\n /**\n * Deletes all messages from the cache.\n * @returns A Promise that resolves when all messages have been deleted.\n */\n public async clear(): Promise<void> {\n const deleteResponse = await this.client.delete(\n this.cacheName,\n this.sessionId\n );\n if (deleteResponse instanceof CacheDelete.Success) {\n // pass\n } else if (deleteResponse instanceof CacheDelete.Error) {\n throw deleteResponse.innerException();\n } else {\n throw new Error(`Unknown response type: ${deleteResponse.toString()}`);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,4BAAb,MAAa,kCAAkCA,6BAAAA,2BAA2B;CACxE,eAAe;EAAC;EAAa;EAAU;EAAW;EAAU;CAE5D;CAEA;CAEA;CAEA;CAEA,YAAoB,OAAuC;AACzD,SAAO;AACP,OAAK,YAAY,MAAM;AACvB,OAAK,SAAS,MAAM;AACpB,OAAK,YAAY,MAAM;AAEvB,OAAK,mBAAmB,MAAM,WAAW;AACzC,OAAK,aACH,MAAM,eAAe,KAAA,IACjBC,oBAAAA,cAAc,GAAG,MAAM,WAAW,GACl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