{"version":3,"file":"momento.cjs","names":["BaseCache","props: MomentoCacheProps","ensureCacheExists","ttlSeconds?: number","InvalidArgumentError","prompt: string","llmKey: string","CacheGet","deserializeStoredGeneration","value: Generation[]","serializeGeneration","CacheSet"],"sources":["../../src/caches/momento.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport {\n  ICacheClient,\n  CacheGet,\n  CacheSet,\n  InvalidArgumentError,\n} from \"@gomomento/sdk-core\";\n\nimport {\n  BaseCache,\n  deserializeStoredGeneration,\n  serializeGeneration,\n} from \"@langchain/core/caches\";\nimport { Generation } from \"@langchain/core/outputs\";\n\nimport { ensureCacheExists } from \"../utils/momento.js\";\n\n/**\n * The settings to instantiate the Momento standard cache.\n */\nexport interface MomentoCacheProps {\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. If not specified,\n   * the cache client default is used.\n   */\n  ttlSeconds?: 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 cache that uses Momento as the backing store.\n * See https://gomomento.com.\n * @example\n * ```typescript\n * const cache = new MomentoCache({\n *   client: new CacheClient({\n *     configuration: Configurations.Laptop.v1(),\n *     credentialProvider: CredentialProvider.fromEnvironmentVariable({\n *       environmentVariableName: \"MOMENTO_API_KEY\",\n *     }),\n *     defaultTtlSeconds: 60 * 60 * 24, // Cache TTL set to 24 hours.\n *   }),\n *   cacheName: \"langchain\",\n * });\n * // Initialize the OpenAI model with Momento cache for caching responses\n * const model = new ChatOpenAI({\n *   model: \"gpt-4o-mini\",\n *   cache,\n * });\n * await model.invoke(\"How are you today?\");\n * const cachedValues = await cache.lookup(\"How are you today?\", \"llmKey\");\n * ```\n */\nexport class MomentoCache extends BaseCache {\n  private client: ICacheClient;\n\n  private readonly cacheName: string;\n\n  private readonly ttlSeconds?: number;\n\n  private constructor(props: MomentoCacheProps) {\n    super();\n    this.client = props.client;\n    this.cacheName = props.cacheName;\n\n    this.validateTtlSeconds(props.ttlSeconds);\n    this.ttlSeconds = props.ttlSeconds;\n  }\n\n  /**\n   * Create a new standard cache backed by Momento.\n   *\n   * @param {MomentoCacheProps} props The settings to instantiate the cache.\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.ttlSeconds The time to live for the cache items. If not specified,\n   * 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. Defaults to true.\n   * @throws {@link InvalidArgumentError} if {@link props.ttlSeconds} is not strictly positive.\n   * @returns The Momento-backed cache.\n   */\n  public static async fromProps(\n    props: MomentoCacheProps\n  ): Promise<MomentoCache> {\n    const instance = new MomentoCache(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   * Lookup LLM generations in cache by prompt and associated LLM key.\n   * @param prompt The prompt to lookup.\n   * @param llmKey The LLM key to lookup.\n   * @returns The generations associated with the prompt and LLM key, or null if not found.\n   */\n  public async lookup(\n    prompt: string,\n    llmKey: string\n  ): Promise<Generation[] | null> {\n    const key = this.keyEncoder(prompt, llmKey);\n    const getResponse = await this.client.get(this.cacheName, key);\n\n    if (getResponse instanceof CacheGet.Hit) {\n      const value = getResponse.valueString();\n      const parsedValue = JSON.parse(value);\n      if (!Array.isArray(parsedValue)) {\n        return null;\n      }\n      return JSON.parse(value).map(deserializeStoredGeneration);\n    } else if (getResponse instanceof CacheGet.Miss) {\n      return null;\n    } else if (getResponse instanceof CacheGet.Error) {\n      throw getResponse.innerException();\n    } else {\n      throw new Error(`Unknown response type: ${getResponse.toString()}`);\n    }\n  }\n\n  /**\n   * Update the cache with the given generations.\n   *\n   * Note this overwrites any existing generations for the given prompt and LLM key.\n   *\n   * @param prompt The prompt to update.\n   * @param llmKey The LLM key to update.\n   * @param value The generations to store.\n   */\n  public async update(\n    prompt: string,\n    llmKey: string,\n    value: Generation[]\n  ): Promise<void> {\n    const key = this.keyEncoder(prompt, llmKey);\n    const setResponse = await this.client.set(\n      this.cacheName,\n      key,\n      JSON.stringify(value.map(serializeGeneration)),\n      { ttl: this.ttlSeconds }\n    );\n\n    if (setResponse instanceof CacheSet.Success) {\n      // pass\n    } else if (setResponse instanceof CacheSet.Error) {\n      throw setResponse.innerException();\n    } else {\n      throw new Error(`Unknown response type: ${setResponse.toString()}`);\n    }\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,IAAa,eAAb,MAAa,qBAAqBA,kCAAU;CAC1C,AAAQ;CAER,AAAiB;CAEjB,AAAiB;CAEjB,AAAQ,YAAYC,OAA0B;EAC5C,OAAO;EACP,KAAK,SAAS,MAAM;EACpB,KAAK,YAAY,MAAM;EAEvB,KAAK,mBAAmB,MAAM,WAAW;EACzC,KAAK,aAAa,MAAM;CACzB;;;;;;;;;;;;;;CAeD,aAAoB,UAClBA,OACuB;EACvB,MAAM,WAAW,IAAI,aAAa;AAClC,MAAI,MAAM,qBAAqB,MAAM,sBAAsB,QACzD,MAAMC,kCAAkB,MAAM,QAAQ,MAAM,UAAU;AAExD,SAAO;CACR;;;;;CAMD,AAAQ,mBAAmBC,YAA2B;AACpD,MAAI,eAAe,UAAa,cAAc,EAC5C,OAAM,IAAIC,0CAAqB;CAElC;;;;;;;CAQD,MAAa,OACXC,QACAC,QAC8B;EAC9B,MAAM,MAAM,KAAK,WAAW,QAAQ,OAAO;EAC3C,MAAM,cAAc,MAAM,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