@langchain/community
Version:
Third-party integrations for LangChain.js
1 lines • 8.38 kB
Source Map (JSON)
{"version":3,"file":"momento.cjs","names":["BaseListChatMessageHistory","props: MomentoChatMessageHistoryProps","CollectionTtl","ensureCacheExists","ttlSeconds?: number","InvalidArgumentError","messages: StoredMessage[]","CacheListFetch","message: BaseMessage","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,yDAA2B;CACxE,eAAe;EAAC;EAAa;EAAU;EAAW;CAAU;CAE5D,AAAiB;CAEjB,AAAiB;CAEjB,AAAiB;CAEjB,AAAiB;CAEjB,AAAQ,YAAYC,OAAuC;EACzD,OAAO;EACP,KAAK,YAAY,MAAM;EACvB,KAAK,SAAS,MAAM;EACpB,KAAK,YAAY,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