{"version":3,"file":"caches_documentdb.cjs","names":["BaseCache","MongoClient","AzureDocumentDBSimilarityType","AzureDocumentDBVectorStore","Document"],"sources":["../../src/caches/caches_documentdb.ts"],"sourcesContent":["import {\n  BaseCache,\n  deserializeStoredGeneration,\n  serializeGeneration,\n} from \"@langchain/core/caches\";\nimport { Generation } from \"@langchain/core/outputs\";\nimport { Document } from \"@langchain/core/documents\";\nimport { EmbeddingsInterface } from \"@langchain/core/embeddings\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { MongoClient } from \"mongodb\";\nimport {\n  AzureDocumentDBConfig,\n  AzureDocumentDBVectorStore,\n  AzureDocumentDBSimilarityType,\n} from \"../azure_documentdb.js\";\n\n/**\n * Represents a Semantic Cache that uses Azure DocumentDB as the underlying\n * storage system.\n *\n * @example\n * ```typescript\n * const embeddings = new OpenAIEmbeddings();\n * const cache = new AzureDocumentDBSemanticCache(embeddings, {\n *   client?: MongoClient\n * });\n * const model = new ChatOpenAI({ model: \"gpt-4o-mini\", cache });\n *\n * // Invoke the model to perform an action\n * const response = await model.invoke(\"Do something random!\");\n * console.log(response);\n * ```\n */\nexport class AzureDocumentDBSemanticCache extends BaseCache {\n  private embeddings: EmbeddingsInterface;\n\n  private config: AzureDocumentDBConfig;\n\n  private similarityScoreThreshold: number;\n\n  private cacheDict: { [key: string]: AzureDocumentDBVectorStore } = {};\n\n  private readonly client: MongoClient | undefined;\n\n  private vectorDistanceFunction: string;\n\n  constructor(\n    embeddings: EmbeddingsInterface,\n    dbConfig: AzureDocumentDBConfig,\n    similarityScoreThreshold: number = 0.6\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(\n        \"AzureDocumentDBSemanticCache client or connection string must be set.\"\n      );\n    }\n\n    if (!dbConfig.client) {\n      this.client = new MongoClient(connectionString!, {\n        appName: \"langchainjs\",\n      });\n    } else {\n      this.client = dbConfig.client;\n    }\n\n    this.config = {\n      ...dbConfig,\n      client: this.client,\n      collectionName: dbConfig.collectionName ?? \"semanticCacheContainer\",\n    };\n\n    this.similarityScoreThreshold = similarityScoreThreshold;\n    this.embeddings = embeddings;\n    this.vectorDistanceFunction =\n      dbConfig?.indexOptions?.similarity ?? AzureDocumentDBSimilarityType.COS;\n  }\n\n  private getLlmCache(llmKey: string) {\n    const key = this.keyEncoder(llmKey);\n    if (!this.cacheDict[key]) {\n      this.cacheDict[key] = new AzureDocumentDBVectorStore(\n        this.embeddings,\n        this.config\n      );\n    }\n    return this.cacheDict[key];\n  }\n\n  /**\n   * Retrieves data from the cache.\n   *\n   * @param prompt The prompt for lookup.\n   * @param llmKey The LLM key used to construct the cache key.\n   * @returns An array of Generations if found, null otherwise.\n   */\n  async lookup(prompt: string, llmKey: string): Promise<Generation[] | null> {\n    const llmCache = this.getLlmCache(llmKey);\n\n    const queryEmbedding = await this.embeddings.embedQuery(prompt);\n    const results = await llmCache.similaritySearchVectorWithScore(\n      queryEmbedding,\n      1,\n      this.config.indexOptions?.indexType\n    );\n    if (!results.length) return null;\n\n    const generations = results\n      .flatMap(([document, score]) => {\n        const isSimilar =\n          (this.vectorDistanceFunction === AzureDocumentDBSimilarityType.L2 &&\n            score <= this.similarityScoreThreshold) ||\n          (this.vectorDistanceFunction !== AzureDocumentDBSimilarityType.L2 &&\n            score >= this.similarityScoreThreshold);\n\n        if (!isSimilar) return undefined;\n\n        return document.metadata.return_value.map((gen: string) =>\n          deserializeStoredGeneration(JSON.parse(gen))\n        );\n      })\n      .filter((gen) => gen !== undefined);\n\n    return generations.length > 0 ? generations : null;\n  }\n\n  /**\n   * Updates the cache with new data.\n   *\n   * @param prompt The prompt for update.\n   * @param llmKey The LLM key used to construct the cache key.\n   * @param value The value to be stored in the cache.\n   */\n  public async update(\n    prompt: string,\n    llmKey: string,\n    returnValue: Generation[]\n  ): Promise<void> {\n    const serializedGenerations = returnValue.map((generation) =>\n      JSON.stringify(serializeGeneration(generation))\n    );\n\n    const llmCache = this.getLlmCache(llmKey);\n\n    const metadata = {\n      llm_string: llmKey,\n      prompt,\n      return_value: serializedGenerations,\n    };\n\n    const doc = new Document({\n      pageContent: prompt,\n      metadata,\n    });\n\n    await llmCache.addDocuments([doc]);\n  }\n\n  /**\n   * Deletes the semantic cache for a given llmKey.\n   * @param llmKey\n   */\n  public async clear(llmKey: string) {\n    const key = this.keyEncoder(llmKey);\n    if (this.cacheDict[key]) {\n      await this.cacheDict[key].delete();\n    }\n  }\n}\n\n// ============================================================================\n// Deprecated aliases for backwards compatibility\n// ============================================================================\n\n/**\n * @deprecated Use `AzureDocumentDBSemanticCache` instead. This alias will be removed in a future version.\n */\nexport const AzureCosmosDBMongoDBSemanticCache = AzureDocumentDBSemanticCache;\n\n/**\n * @deprecated Use `AzureDocumentDBSemanticCache` instead. This alias will be removed in a future version.\n */\nexport type AzureCosmosDBMongoDBSemanticCache = AzureDocumentDBSemanticCache;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,+BAAb,cAAkDA,iCAAU;CAC1D,AAAQ;CAER,AAAQ;CAER,AAAQ;CAER,AAAQ,YAA2D,EAAE;CAErE,AAAiB;CAEjB,AAAQ;CAER,YACE,YACA,UACA,2BAAmC,IACnC;AACA,SAAO;EAEP,MAAM,mBACJ,SAAS,0EACc,qCAAqC,0DACrC,2CAA2C;AAEpE,MAAI,CAAC,SAAS,UAAU,CAAC,iBACvB,OAAM,IAAI,MACR,wEACD;AAGH,MAAI,CAAC,SAAS,OACZ,MAAK,SAAS,IAAIC,oBAAY,kBAAmB,EAC/C,SAAS,eACV,CAAC;MAEF,MAAK,SAAS,SAAS;AAGzB,OAAK,SAAS;GACZ,GAAG;GACH,QAAQ,KAAK;GACb,gBAAgB,SAAS,kBAAkB;GAC5C;AAED,OAAK,2BAA2B;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