index.cjs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. var desc = Object.getOwnPropertyDescriptor(m, k);
  5. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  6. desc = { enumerable: true, get: function() { return m[k]; } };
  7. }
  8. Object.defineProperty(o, k2, desc);
  9. }) : (function(o, m, k, k2) {
  10. if (k2 === undefined) k2 = k;
  11. o[k2] = m[k];
  12. }));
  13. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  14. Object.defineProperty(o, "default", { enumerable: true, value: v });
  15. }) : function(o, v) {
  16. o["default"] = v;
  17. });
  18. var __importStar = (this && this.__importStar) || function (mod) {
  19. if (mod && mod.__esModule) return mod;
  20. var result = {};
  21. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  22. __setModuleDefault(result, mod);
  23. return result;
  24. };
  25. Object.defineProperty(exports, "__esModule", { value: true });
  26. exports.load = void 0;
  27. const serializable_js_1 = require("./serializable.cjs");
  28. const import_constants_js_1 = require("./import_constants.cjs");
  29. const coreImportMap = __importStar(require("./import_map.cjs"));
  30. const map_keys_js_1 = require("./map_keys.cjs");
  31. const env_js_1 = require("../utils/env.cjs");
  32. function combineAliasesAndInvert(constructor) {
  33. const aliases = {};
  34. for (
  35. // eslint-disable-next-line @typescript-eslint/no-this-alias
  36. let current = constructor; current && current.prototype; current = Object.getPrototypeOf(current)) {
  37. Object.assign(aliases, Reflect.get(current.prototype, "lc_aliases"));
  38. }
  39. return Object.entries(aliases).reduce((acc, [key, value]) => {
  40. acc[value] = key;
  41. return acc;
  42. }, {});
  43. }
  44. async function reviver(value) {
  45. const { optionalImportsMap = {}, optionalImportEntrypoints = [], importMap = {}, secretsMap = {}, path = ["$"], } = this;
  46. const pathStr = path.join(".");
  47. if (typeof value === "object" &&
  48. value !== null &&
  49. !Array.isArray(value) &&
  50. "lc" in value &&
  51. "type" in value &&
  52. "id" in value &&
  53. value.lc === 1 &&
  54. value.type === "secret") {
  55. const serialized = value;
  56. const [key] = serialized.id;
  57. if (key in secretsMap) {
  58. return secretsMap[key];
  59. }
  60. else {
  61. const secretValueInEnv = (0, env_js_1.getEnvironmentVariable)(key);
  62. if (secretValueInEnv) {
  63. return secretValueInEnv;
  64. }
  65. else {
  66. throw new Error(`Missing key "${key}" for ${pathStr} in load(secretsMap={})`);
  67. }
  68. }
  69. }
  70. else if (typeof value === "object" &&
  71. value !== null &&
  72. !Array.isArray(value) &&
  73. "lc" in value &&
  74. "type" in value &&
  75. "id" in value &&
  76. value.lc === 1 &&
  77. value.type === "not_implemented") {
  78. const serialized = value;
  79. const str = JSON.stringify(serialized);
  80. throw new Error(`Trying to load an object that doesn't implement serialization: ${pathStr} -> ${str}`);
  81. }
  82. else if (typeof value === "object" &&
  83. value !== null &&
  84. !Array.isArray(value) &&
  85. "lc" in value &&
  86. "type" in value &&
  87. "id" in value &&
  88. "kwargs" in value &&
  89. value.lc === 1) {
  90. const serialized = value;
  91. const str = JSON.stringify(serialized);
  92. const [name, ...namespaceReverse] = serialized.id.slice().reverse();
  93. const namespace = namespaceReverse.reverse();
  94. const importMaps = { langchain_core: coreImportMap, langchain: importMap };
  95. let module = null;
  96. const optionalImportNamespaceAliases = [namespace.join("/")];
  97. if (namespace[0] === "langchain_community") {
  98. optionalImportNamespaceAliases.push(["langchain", ...namespace.slice(1)].join("/"));
  99. }
  100. const matchingNamespaceAlias = optionalImportNamespaceAliases.find((alias) => alias in optionalImportsMap);
  101. if (import_constants_js_1.optionalImportEntrypoints
  102. .concat(optionalImportEntrypoints)
  103. .includes(namespace.join("/")) ||
  104. matchingNamespaceAlias) {
  105. if (matchingNamespaceAlias !== undefined) {
  106. module = await optionalImportsMap[matchingNamespaceAlias];
  107. }
  108. else {
  109. throw new Error(`Missing key "${namespace.join("/")}" for ${pathStr} in load(optionalImportsMap={})`);
  110. }
  111. }
  112. else {
  113. let finalImportMap;
  114. // Currently, we only support langchain and langchain_core imports.
  115. if (namespace[0] === "langchain" || namespace[0] === "langchain_core") {
  116. finalImportMap = importMaps[namespace[0]];
  117. namespace.shift();
  118. }
  119. else {
  120. throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);
  121. }
  122. // The root namespace "langchain" is not a valid import.
  123. if (namespace.length === 0) {
  124. throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);
  125. }
  126. // Find the longest matching namespace.
  127. let importMapKey;
  128. do {
  129. importMapKey = namespace.join("__");
  130. if (importMapKey in finalImportMap) {
  131. break;
  132. }
  133. else {
  134. namespace.pop();
  135. }
  136. } while (namespace.length > 0);
  137. // If no matching namespace is found, throw an error.
  138. if (importMapKey in finalImportMap) {
  139. module = finalImportMap[importMapKey];
  140. }
  141. }
  142. if (typeof module !== "object" || module === null) {
  143. throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);
  144. }
  145. // Extract the builder from the import map.
  146. const builder =
  147. // look for a named export with the same name as the class
  148. module[name] ??
  149. // look for an export with a lc_name property matching the class name
  150. // this is necessary for classes that are minified
  151. Object.values(module).find((v) => typeof v === "function" &&
  152. (0, serializable_js_1.get_lc_unique_name)(v) === name);
  153. if (typeof builder !== "function") {
  154. throw new Error(`Invalid identifer: ${pathStr} -> ${str}`);
  155. }
  156. // Recurse on the arguments, which may be serialized objects themselves
  157. const kwargs = await reviver.call({ ...this, path: [...path, "kwargs"] }, serialized.kwargs);
  158. // Construct the object
  159. if (serialized.type === "constructor") {
  160. // eslint-disable-next-line new-cap, @typescript-eslint/no-explicit-any
  161. const instance = new builder((0, map_keys_js_1.mapKeys)(kwargs, map_keys_js_1.keyFromJson, combineAliasesAndInvert(builder)));
  162. // Minification in severless/edge runtimes will mange the
  163. // name of classes presented in traces. As the names in import map
  164. // are present as-is even with minification, use these names instead
  165. Object.defineProperty(instance.constructor, "name", { value: name });
  166. return instance;
  167. }
  168. else {
  169. throw new Error(`Invalid type: ${pathStr} -> ${str}`);
  170. }
  171. }
  172. else if (typeof value === "object" && value !== null) {
  173. if (Array.isArray(value)) {
  174. return Promise.all(value.map((v, i) => reviver.call({ ...this, path: [...path, `${i}`] }, v)));
  175. }
  176. else {
  177. return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, value]) => [
  178. key,
  179. await reviver.call({ ...this, path: [...path, key] }, value),
  180. ])));
  181. }
  182. }
  183. return value;
  184. }
  185. async function load(text, mappings) {
  186. const json = JSON.parse(text);
  187. return reviver.call({ ...mappings }, json);
  188. }
  189. exports.load = load;