@langchain/core
Version:
Core LangChain.js abstractions and schemas
91 lines (89 loc) • 4.76 kB
JavaScript
import { keyFromJson, mapKeys } from "./map_keys.js";
import { get_lc_unique_name } from "./serializable.js";
import { getEnvironmentVariable } from "../utils/env.js";
import { optionalImportEntrypoints } from "./import_constants.js";
import { import_map_exports } from "./import_map.js";
//#region src/load/index.ts
function combineAliasesAndInvert(constructor) {
const aliases = {};
for (let current = constructor; current && current.prototype; current = Object.getPrototypeOf(current)) Object.assign(aliases, Reflect.get(current.prototype, "lc_aliases"));
return Object.entries(aliases).reduce((acc, [key, value]) => {
acc[value] = key;
return acc;
}, {});
}
async function reviver(value) {
const { optionalImportsMap = {}, optionalImportEntrypoints: optionalImportEntrypoints$1 = [], importMap = {}, secretsMap = {}, path = ["$"] } = this;
const pathStr = path.join(".");
if (typeof value === "object" && value !== null && !Array.isArray(value) && "lc" in value && "type" in value && "id" in value && value.lc === 1 && value.type === "secret") {
const serialized = value;
const [key] = serialized.id;
if (key in secretsMap) return secretsMap[key];
else {
const secretValueInEnv = getEnvironmentVariable(key);
if (secretValueInEnv) return secretValueInEnv;
else throw new Error(`Missing key "${key}" for ${pathStr} in load(secretsMap={})`);
}
} else if (typeof value === "object" && value !== null && !Array.isArray(value) && "lc" in value && "type" in value && "id" in value && value.lc === 1 && value.type === "not_implemented") {
const serialized = value;
const str = JSON.stringify(serialized);
throw new Error(`Trying to load an object that doesn't implement serialization: ${pathStr} -> ${str}`);
} else if (typeof value === "object" && value !== null && !Array.isArray(value) && "lc" in value && "type" in value && "id" in value && "kwargs" in value && value.lc === 1) {
const serialized = value;
const str = JSON.stringify(serialized);
const [name, ...namespaceReverse] = serialized.id.slice().reverse();
const namespace = namespaceReverse.reverse();
const importMaps = {
langchain_core: import_map_exports,
langchain: importMap
};
let module = null;
const optionalImportNamespaceAliases = [namespace.join("/")];
if (namespace[0] === "langchain_community") optionalImportNamespaceAliases.push(["langchain", ...namespace.slice(1)].join("/"));
const matchingNamespaceAlias = optionalImportNamespaceAliases.find((alias) => alias in optionalImportsMap);
if (optionalImportEntrypoints.concat(optionalImportEntrypoints$1).includes(namespace.join("/")) || matchingNamespaceAlias) if (matchingNamespaceAlias !== void 0) module = await optionalImportsMap[matchingNamespaceAlias];
else throw new Error(`Missing key "${namespace.join("/")}" for ${pathStr} in load(optionalImportsMap={})`);
else {
let finalImportMap;
if (namespace[0] === "langchain" || namespace[0] === "langchain_core") {
finalImportMap = importMaps[namespace[0]];
namespace.shift();
} else throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);
if (namespace.length === 0) throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);
let importMapKey;
do {
importMapKey = namespace.join("__");
if (importMapKey in finalImportMap) break;
else namespace.pop();
} while (namespace.length > 0);
if (importMapKey in finalImportMap) module = finalImportMap[importMapKey];
}
if (typeof module !== "object" || module === null) throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);
const builder = module[name] ?? Object.values(module).find((v) => typeof v === "function" && get_lc_unique_name(v) === name);
if (typeof builder !== "function") throw new Error(`Invalid identifer: ${pathStr} -> ${str}`);
const kwargs = await reviver.call({
...this,
path: [...path, "kwargs"]
}, serialized.kwargs);
if (serialized.type === "constructor") {
const instance = new builder(mapKeys(kwargs, keyFromJson, combineAliasesAndInvert(builder)));
Object.defineProperty(instance.constructor, "name", { value: name });
return instance;
} else throw new Error(`Invalid type: ${pathStr} -> ${str}`);
} else if (typeof value === "object" && value !== null) if (Array.isArray(value)) return Promise.all(value.map((v, i) => reviver.call({
...this,
path: [...path, `${i}`]
}, v)));
else return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, value$1]) => [key, await reviver.call({
...this,
path: [...path, key]
}, value$1)])));
return value;
}
async function load(text, mappings) {
const json = JSON.parse(text);
return reviver.call({ ...mappings }, json);
}
//#endregion
export { load };
//# sourceMappingURL=index.js.map