{"version":3,"file":"documentdb.cjs","names":["BaseListChatMessageHistory","MongoClient"],"sources":["../../src/chat_histories/documentdb.ts"],"sourcesContent":["import {\n  Collection,\n  Document as AzureDocumentDBDocument,\n  PushOperator,\n  Db,\n  MongoClient,\n} from \"mongodb\";\nimport { BaseListChatMessageHistory } from \"@langchain/core/chat_history\";\nimport {\n  BaseMessage,\n  mapChatMessagesToStoredMessages,\n  mapStoredMessagesToChatMessages,\n} from \"@langchain/core/messages\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\n\nexport interface AzureDocumentDBChatHistoryDBConfig {\n  readonly client?: MongoClient;\n  readonly connectionString?: string;\n  readonly databaseName?: string;\n  readonly collectionName?: string;\n}\n\nexport type ChatSessionDocumentDB = {\n  id: string;\n  user_id: string;\n  context: Record<string, unknown>;\n};\n\nconst ID_KEY = \"sessionId\";\nconst ID_USER = \"userId\";\n\n/**\n * Azure DocumentDB Chat Message History.\n * Stores chat message history in an Azure DocumentDB collection.\n */\nexport class AzureDocumentDBChatMessageHistory extends BaseListChatMessageHistory {\n  lc_namespace = [\"langchain\", \"stores\", \"message\", \"azurecosmosdb\"];\n\n  get lc_secrets(): { [key: string]: string } {\n    return {\n      connectionString: \"AZURE_DOCUMENTDB_CONNECTION_STRING\",\n    };\n  }\n\n  private initPromise?: Promise<void>;\n\n  private context: Record<string, unknown> = {};\n\n  private readonly client: MongoClient | undefined;\n\n  private database: Db;\n\n  private collection: Collection<AzureDocumentDBDocument>;\n\n  private sessionId: string;\n\n  private userId: string;\n\n  initialize: () => Promise<void>;\n\n  constructor(\n    dbConfig: AzureDocumentDBChatHistoryDBConfig,\n    sessionId: string,\n    userId: string\n  ) {\n    super();\n\n    const connectionString =\n      dbConfig.connectionString ??\n      getEnvironmentVariable(\"AZURE_DOCUMENTDB_CONNECTION_STRING\") ??\n      getEnvironmentVariable(\"AZURE_COSMOSDB_MONGODB_CONNECTION_STRING\");\n\n    if (!dbConfig.client && !connectionString) {\n      throw new Error(\"Mongo client or connection string must be set.\");\n    }\n\n    if (!dbConfig.client) {\n      this.client = new MongoClient(connectionString!, {\n        appName: \"langchainjs\",\n      });\n    }\n\n    const client = dbConfig.client || this.client!;\n    const databaseName = dbConfig.databaseName ?? \"chatHistoryDB\";\n    const collectionName = dbConfig.collectionName ?? \"chatHistory\";\n\n    this.sessionId = sessionId;\n    this.userId = userId ?? \"anonymous\";\n\n    // Deferring initialization to the first call to `initialize`\n    this.initialize = () => {\n      if (this.initPromise === undefined) {\n        this.initPromise = this.init(\n          client,\n          databaseName,\n          collectionName\n        ).catch((error) => {\n          console.error(\n            \"Error during AzureDocumentDBChatMessageHistory initialization: \",\n            error\n          );\n        });\n      }\n\n      return this.initPromise;\n    };\n  }\n\n  /**\n   * Initializes the AzureDocumentDBChatMessageHistory by connecting to the database.\n   * @param client The MongoClient to use for connecting to the database.\n   * @param databaseName The name of the database to use.\n   * @param collectionName The name of the collection to use.\n   * @returns A promise that resolves when the AzureDocumentDBChatMessageHistory has been initialized.\n   */\n  private async init(\n    client: MongoClient,\n    databaseName: string,\n    collectionName: string\n  ): Promise<void> {\n    this.initPromise = (async () => {\n      await client.connect();\n      this.database = client.db(databaseName);\n      this.collection = this.database.collection(collectionName);\n    })();\n\n    return this.initPromise;\n  }\n\n  /**\n   * Retrieves the messages stored in the history.\n   * @returns A promise that resolves with the messages stored in the history.\n   */\n  async getMessages(): Promise<BaseMessage[]> {\n    await this.initialize();\n\n    const document = await this.collection.findOne({\n      [ID_KEY]: this.sessionId,\n      [ID_USER]: this.userId,\n    });\n    const messages = document?.messages || [];\n    return mapStoredMessagesToChatMessages(messages);\n  }\n\n  /**\n   * Adds a message to the history.\n   * @param message The message to add to the history.\n   * @returns A promise that resolves when the message has been added to the history.\n   */\n  async addMessage(message: BaseMessage): Promise<void> {\n    await this.addMessages([message]);\n  }\n\n  /**\n   * Adds multiple messages to the history.\n   * @param messages The messages to add to the history.\n   * @returns A promise that resolves when the messages have been added to the history.\n   */\n  async addMessages(messages: BaseMessage[]): Promise<void> {\n    await this.initialize();\n\n    const storedMessages = mapChatMessagesToStoredMessages(messages);\n    const context = await this.getContext();\n    await this.collection.updateOne(\n      { [ID_KEY]: this.sessionId, [ID_USER]: this.userId },\n      {\n        $push: {\n          messages: { $each: storedMessages },\n        } as PushOperator<Document>,\n        $set: { context },\n      },\n      { upsert: true }\n    );\n  }\n\n  /**\n   * Clear the history.\n   * @returns A promise that resolves when the history has been cleared.\n   */\n  async clear(): Promise<void> {\n    await this.initialize();\n\n    await this.collection.deleteOne({\n      [ID_KEY]: this.sessionId,\n      [ID_USER]: this.userId,\n    });\n  }\n\n  async getAllSessions(): Promise<ChatSessionDocumentDB[]> {\n    await this.initialize();\n    const documents = await this.collection\n      .find({\n        [ID_USER]: this.userId,\n      })\n      .toArray();\n\n    const chatSessions: ChatSessionDocumentDB[] = documents.map((doc) => ({\n      id: doc[ID_KEY],\n      user_id: doc[ID_USER],\n      context: doc.context || {},\n    }));\n\n    return chatSessions;\n  }\n\n  async clearAllSessions() {\n    await this.initialize();\n    try {\n      await this.collection.deleteMany({\n        [ID_USER]: this.userId,\n      });\n    } catch (error) {\n      console.error(\"Error clearing chat history sessions:\", error);\n      throw error;\n    }\n  }\n\n  async getContext(): Promise<Record<string, unknown>> {\n    await this.initialize();\n\n    const document = await this.collection.findOne({\n      [ID_KEY]: this.sessionId,\n      [ID_USER]: this.userId,\n    });\n    this.context = document?.context || this.context;\n    return this.context;\n  }\n\n  async setContext(context: Record<string, unknown>): Promise<void> {\n    await this.initialize();\n\n    try {\n      await this.collection.updateOne(\n        { [ID_KEY]: this.sessionId },\n        {\n          $set: { context },\n        },\n        { upsert: true }\n      );\n    } catch (error) {\n      console.error(\"Error setting chat history context\", error);\n      throw error;\n    }\n  }\n}\n\n// ============================================================================\n// Deprecated aliases for backwards compatibility\n// ============================================================================\n\n/**\n * @deprecated Use `AzureDocumentDBChatHistoryDBConfig` instead. This alias will be removed in a future version.\n */\nexport type AzureCosmosDBMongoChatHistoryDBConfig =\n  AzureDocumentDBChatHistoryDBConfig;\n\n/**\n * @deprecated Use `ChatSessionDocumentDB` instead. This alias will be removed in a future version.\n */\nexport type ChatSessionMongo = ChatSessionDocumentDB;\n\n/**\n * @deprecated Use `AzureDocumentDBChatMessageHistory` instead. This alias will be removed in a future version.\n */\nexport const AzureCosmosDBMongoChatMessageHistory =\n  AzureDocumentDBChatMessageHistory;\n\n/**\n * @deprecated Use `AzureDocumentDBChatMessageHistory` instead. This alias will be removed in a future version.\n */\nexport type AzureCosmosDBMongoChatMessageHistory =\n  AzureDocumentDBChatMessageHistory;\n"],"mappings":";;;;;;AA4BA,MAAM,SAAS;AACf,MAAM,UAAU;;;;;AAMhB,IAAa,oCAAb,cAAuDA,wDAA2B;CAChF,eAAe;EAAC;EAAa;EAAU;EAAW;EAAgB;CAElE,IAAI,aAAwC;AAC1C,SAAO,EACL,kBAAkB,sCACnB;;CAGH,AAAQ;CAER,AAAQ,UAAmC,EAAE;CAE7C,AAAiB;CAEjB,AAAQ;CAER,AAAQ;CAER,AAAQ;CAER,AAAQ;CAER;CAEA,YACE,UACA,WACA,QACA;AACA,SAAO;EAEP,MAAM,mBACJ,SAAS,0EACc,qCAAqC,0DACrC,2CAA2C;AAEpE,MAAI,CAAC,SAAS,UAAU,CAAC,iBACvB,OAAM,IAAI,MAAM,iDAAiD;AAGnE,MAAI,CAAC,SAAS,OACZ,MAAK,SAAS,IAAIC,oBAAY,kBAAmB,EAC/C,SAAS,eACV,CAAC;EAGJ,MAAM,SAAS,SAAS,UAAU,KAAK;EACvC,MAAM,eAAe,SAAS,gBAAgB;EAC9C,MAAM,iBAAiB,SAAS,kBAAkB;AAElD,OAAK,YAAY;AACjB,OAAK,SAAS,UAAU;AAGxB,OAAK,mBAAmB;AACtB,OAAI,KAAK,gBAAgB,OACvB,MAAK,cAAc,KAAK,KACtB,QACA,cACA,eACD,CAAC,OAAO,UAAU;AACjB,YAAQ,MACN,mEACA,MACD;KACD;AAGJ,UAAO,KAAK;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