@langchain/core 1.1.10 → 1.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/documents/document.cjs.map +1 -1
- package/dist/documents/document.js.map +1 -1
- package/dist/documents/transformers.cjs.map +1 -1
- package/dist/documents/transformers.js.map +1 -1
- package/dist/example_selectors/conditional.cjs.map +1 -1
- package/dist/example_selectors/conditional.js.map +1 -1
- package/dist/example_selectors/semantic_similarity.cjs.map +1 -1
- package/dist/example_selectors/semantic_similarity.js.map +1 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.js.map +1 -1
- package/dist/language_models/chat_models.cjs.map +1 -1
- package/dist/language_models/chat_models.js.map +1 -1
- package/dist/language_models/llms.cjs.map +1 -1
- package/dist/language_models/llms.js.map +1 -1
- package/dist/load/import_map.cjs +11 -11
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +11 -11
- package/dist/load/import_map.js.map +1 -1
- package/dist/load/index.cjs.map +1 -1
- package/dist/load/index.js.map +1 -1
- package/dist/load/serializable.cjs +3 -3
- package/dist/load/serializable.cjs.map +1 -1
- package/dist/load/serializable.js +3 -3
- package/dist/load/serializable.js.map +1 -1
- package/dist/load/validation.cjs +13 -7
- package/dist/load/validation.cjs.map +1 -1
- package/dist/load/validation.js +13 -7
- package/dist/load/validation.js.map +1 -1
- package/dist/messages/ai.cjs.map +1 -1
- package/dist/messages/ai.js.map +1 -1
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.js.map +1 -1
- package/dist/messages/chat.cjs.map +1 -1
- package/dist/messages/chat.js.map +1 -1
- package/dist/messages/content/data.cjs.map +1 -1
- package/dist/messages/content/data.js.map +1 -1
- package/dist/messages/content/index.cjs.map +1 -1
- package/dist/messages/content/index.js.map +1 -1
- package/dist/messages/content/tools.cjs.map +1 -1
- package/dist/messages/content/tools.js.map +1 -1
- package/dist/messages/function.cjs.map +1 -1
- package/dist/messages/function.js.map +1 -1
- package/dist/messages/human.cjs.map +1 -1
- package/dist/messages/human.js.map +1 -1
- package/dist/messages/message.cjs.map +1 -1
- package/dist/messages/message.js.map +1 -1
- package/dist/messages/modifier.cjs.map +1 -1
- package/dist/messages/modifier.js.map +1 -1
- package/dist/messages/system.cjs.map +1 -1
- package/dist/messages/system.js.map +1 -1
- package/dist/messages/tool.cjs.map +1 -1
- package/dist/messages/tool.js.map +1 -1
- package/dist/messages/utils.cjs.map +1 -1
- package/dist/messages/utils.js.map +1 -1
- package/dist/output_parsers/base.cjs.map +1 -1
- package/dist/output_parsers/base.js.map +1 -1
- package/dist/output_parsers/index.cjs +1 -1
- package/dist/output_parsers/index.js +1 -1
- package/dist/output_parsers/json.cjs.map +1 -1
- package/dist/output_parsers/json.js.map +1 -1
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.cjs.map +1 -1
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.js.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.js.map +1 -1
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.js.map +1 -1
- package/dist/output_parsers/transform.cjs.map +1 -1
- package/dist/output_parsers/transform.js.map +1 -1
- package/dist/prompts/base.cjs.map +1 -1
- package/dist/prompts/base.js.map +1 -1
- package/dist/prompts/chat.cjs.map +1 -1
- package/dist/prompts/chat.js.map +1 -1
- package/dist/prompts/dict.cjs.map +1 -1
- package/dist/prompts/dict.js.map +1 -1
- package/dist/prompts/few_shot.cjs.map +1 -1
- package/dist/prompts/few_shot.js.map +1 -1
- package/dist/prompts/image.cjs.map +1 -1
- package/dist/prompts/image.js.map +1 -1
- package/dist/prompts/pipeline.cjs.map +1 -1
- package/dist/prompts/pipeline.js.map +1 -1
- package/dist/prompts/prompt.cjs.map +1 -1
- package/dist/prompts/prompt.js.map +1 -1
- package/dist/prompts/string.cjs.map +1 -1
- package/dist/prompts/string.js.map +1 -1
- package/dist/prompts/structured.cjs.map +1 -1
- package/dist/prompts/structured.js.map +1 -1
- package/dist/prompts/template.cjs +1 -4
- package/dist/prompts/template.cjs.map +1 -1
- package/dist/prompts/template.js +1 -4
- package/dist/prompts/template.js.map +1 -1
- package/dist/retrievers/index.cjs.map +1 -1
- package/dist/retrievers/index.js.map +1 -1
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.js.map +1 -1
- package/dist/runnables/branch.cjs.map +1 -1
- package/dist/runnables/branch.js.map +1 -1
- package/dist/runnables/history.cjs.map +1 -1
- package/dist/runnables/history.js.map +1 -1
- package/dist/runnables/passthrough.cjs.map +1 -1
- package/dist/runnables/passthrough.js.map +1 -1
- package/dist/runnables/router.cjs.map +1 -1
- package/dist/runnables/router.js.map +1 -1
- package/dist/singletons/callbacks.cjs.map +1 -1
- package/dist/singletons/callbacks.js.map +1 -1
- package/dist/stores.d.cts.map +1 -1
- package/dist/structured_query/base.cjs.map +1 -1
- package/dist/structured_query/base.js.map +1 -1
- package/dist/structured_query/ir.cjs.map +1 -1
- package/dist/structured_query/ir.js.map +1 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.js.map +1 -1
- package/dist/utils/async_caller.cjs.map +1 -1
- package/dist/utils/async_caller.js.map +1 -1
- package/dist/utils/stream.cjs.map +1 -1
- package/dist/utils/stream.js.map +1 -1
- package/dist/utils/testing/chat_models.cjs.map +1 -1
- package/dist/utils/testing/chat_models.js.map +1 -1
- package/dist/utils/testing/tools.cjs.map +1 -1
- package/dist/utils/testing/tools.js.map +1 -1
- package/dist/utils/types/zod.cjs.map +1 -1
- package/dist/utils/types/zod.js.map +1 -1
- package/dist/vectorstores.cjs.map +1 -1
- package/dist/vectorstores.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"structured.js","names":["x: unknown","input: StructuredPromptInput<RunInput, PartialVariableName>","coerceable: RunnableLike<ChatPromptValueInterface, NewRunOutput>","promptMessages: (\n | ChatPromptTemplate<InputValues, string>\n | BaseMessagePromptTemplateLike\n )[]","schema: StructuredPromptInput[\"schema\"]","method?: \"jsonMode\" | \"jsonSchema\" | \"functionMode\""],"sources":["../../src/prompts/structured.ts"],"sourcesContent":["import { ChatPromptValueInterface } from \"../prompt_values.js\";\nimport { RunnableLike, Runnable, RunnableBinding } from \"../runnables/base.js\";\nimport { RunnableConfig } from \"../runnables/config.js\";\nimport { InputValues } from \"../utils/types/index.js\";\nimport {\n BaseMessagePromptTemplateLike,\n ChatPromptTemplate,\n ChatPromptTemplateInput,\n} from \"./chat.js\";\n\nfunction isWithStructuredOutput(x: unknown): x is {\n withStructuredOutput: (...arg: unknown[]) => Runnable;\n} {\n return (\n typeof x === \"object\" &&\n x != null &&\n \"withStructuredOutput\" in x &&\n typeof x.withStructuredOutput === \"function\"\n );\n}\n\nfunction isRunnableBinding(x: unknown): x is RunnableBinding<unknown, unknown> {\n return (\n typeof x === \"object\" &&\n x != null &&\n \"lc_id\" in x &&\n Array.isArray(x.lc_id) &&\n x.lc_id.join(\"/\") === \"langchain_core/runnables/RunnableBinding\"\n );\n}\n\n/**\n * Interface for the input of a ChatPromptTemplate.\n */\nexport interface StructuredPromptInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any
|
|
1
|
+
{"version":3,"file":"structured.js","names":["x: unknown","input: StructuredPromptInput<RunInput, PartialVariableName>","coerceable: RunnableLike<ChatPromptValueInterface, NewRunOutput>","promptMessages: (\n | ChatPromptTemplate<InputValues, string>\n | BaseMessagePromptTemplateLike\n )[]","schema: StructuredPromptInput[\"schema\"]","method?: \"jsonMode\" | \"jsonSchema\" | \"functionMode\""],"sources":["../../src/prompts/structured.ts"],"sourcesContent":["import { ChatPromptValueInterface } from \"../prompt_values.js\";\nimport { RunnableLike, Runnable, RunnableBinding } from \"../runnables/base.js\";\nimport { RunnableConfig } from \"../runnables/config.js\";\nimport { InputValues } from \"../utils/types/index.js\";\nimport {\n BaseMessagePromptTemplateLike,\n ChatPromptTemplate,\n ChatPromptTemplateInput,\n} from \"./chat.js\";\n\nfunction isWithStructuredOutput(x: unknown): x is {\n withStructuredOutput: (...arg: unknown[]) => Runnable;\n} {\n return (\n typeof x === \"object\" &&\n x != null &&\n \"withStructuredOutput\" in x &&\n typeof x.withStructuredOutput === \"function\"\n );\n}\n\nfunction isRunnableBinding(x: unknown): x is RunnableBinding<unknown, unknown> {\n return (\n typeof x === \"object\" &&\n x != null &&\n \"lc_id\" in x &&\n Array.isArray(x.lc_id) &&\n x.lc_id.join(\"/\") === \"langchain_core/runnables/RunnableBinding\"\n );\n}\n\n/**\n * Interface for the input of a ChatPromptTemplate.\n */\nexport interface StructuredPromptInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n> extends ChatPromptTemplateInput<RunInput, PartialVariableName> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schema: Record<string, any>;\n method?: \"jsonMode\" | \"jsonSchema\" | \"functionMode\";\n}\n\nexport class StructuredPrompt<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n >\n extends ChatPromptTemplate<RunInput, PartialVariableName>\n implements StructuredPromptInput<RunInput, PartialVariableName>\n{\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schema: Record<string, any>;\n\n method?: \"jsonMode\" | \"jsonSchema\" | \"functionMode\";\n\n lc_namespace = [\"langchain_core\", \"prompts\", \"structured\"];\n\n get lc_aliases(): Record<string, string> {\n return {\n ...super.lc_aliases,\n schema: \"schema_\",\n };\n }\n\n constructor(input: StructuredPromptInput<RunInput, PartialVariableName>) {\n super(input);\n this.schema = input.schema;\n this.method = input.method;\n }\n\n pipe<NewRunOutput>(\n coerceable: RunnableLike<ChatPromptValueInterface, NewRunOutput>\n ): Runnable<RunInput, Exclude<NewRunOutput, Error>, RunnableConfig> {\n if (isWithStructuredOutput(coerceable)) {\n return super.pipe(coerceable.withStructuredOutput(this.schema));\n }\n\n if (\n isRunnableBinding(coerceable) &&\n isWithStructuredOutput(coerceable.bound)\n ) {\n return super.pipe(\n new RunnableBinding({\n bound: coerceable.bound.withStructuredOutput(\n this.schema,\n ...(this.method ? [{ method: this.method }] : [])\n ),\n kwargs: coerceable.kwargs ?? {},\n config: coerceable.config,\n configFactories: coerceable.configFactories,\n })\n );\n }\n\n throw new Error(\n `Structured prompts need to be piped to a language model that supports the \"withStructuredOutput()\" method.`\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static fromMessagesAndSchema<RunInput extends InputValues = any>(\n promptMessages: (\n | ChatPromptTemplate<InputValues, string>\n | BaseMessagePromptTemplateLike\n )[],\n schema: StructuredPromptInput[\"schema\"],\n method?: \"jsonMode\" | \"jsonSchema\" | \"functionMode\"\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): ChatPromptTemplate<RunInput, any> {\n return StructuredPrompt.fromMessages<\n RunInput,\n StructuredPromptInput<RunInput>\n >(promptMessages, { schema, method });\n }\n}\n"],"mappings":";;;;AAUA,SAAS,uBAAuBA,GAE9B;AACA,QACE,OAAO,MAAM,YACb,KAAK,QACL,0BAA0B,KAC1B,OAAO,EAAE,yBAAyB;AAErC;AAED,SAAS,kBAAkBA,GAAoD;AAC7E,QACE,OAAO,MAAM,YACb,KAAK,QACL,WAAW,KACX,MAAM,QAAQ,EAAE,MAAM,IACtB,EAAE,MAAM,KAAK,IAAI,KAAK;AAEzB;AAgBD,IAAa,mBAAb,MAAa,yBAMH,mBAEV;CAEE;CAEA;CAEA,eAAe;EAAC;EAAkB;EAAW;CAAa;CAE1D,IAAI,aAAqC;AACvC,SAAO;GACL,GAAG,MAAM;GACT,QAAQ;EACT;CACF;CAED,YAAYC,OAA6D;EACvE,MAAM,MAAM;EACZ,KAAK,SAAS,MAAM;EACpB,KAAK,SAAS,MAAM;CACrB;CAED,KACEC,YACkE;AAClE,MAAI,uBAAuB,WAAW,CACpC,QAAO,MAAM,KAAK,WAAW,qBAAqB,KAAK,OAAO,CAAC;AAGjE,MACE,kBAAkB,WAAW,IAC7B,uBAAuB,WAAW,MAAM,CAExC,QAAO,MAAM,KACX,IAAI,gBAAgB;GAClB,OAAO,WAAW,MAAM,qBACtB,KAAK,QACL,GAAI,KAAK,SAAS,CAAC,EAAE,QAAQ,KAAK,OAAQ,CAAC,IAAG,CAAE,EACjD;GACD,QAAQ,WAAW,UAAU,CAAE;GAC/B,QAAQ,WAAW;GACnB,iBAAiB,WAAW;EAC7B,GACF;AAGH,QAAM,IAAI,MACR,CAAC,0GAA0G,CAAC;CAE/G;CAGD,OAAO,sBACLC,gBAIAC,QACAC,QAEmC;AACnC,SAAO,iBAAiB,aAGtB,gBAAgB;GAAE;GAAQ;EAAQ,EAAC;CACtC;AACF"}
|
|
@@ -128,10 +128,7 @@ const checkValidTemplate = (template, templateFormat, inputVariables) => {
|
|
|
128
128
|
should be one of ${validFormats}`);
|
|
129
129
|
}
|
|
130
130
|
try {
|
|
131
|
-
const dummyInputs = inputVariables.
|
|
132
|
-
acc[v] = "foo";
|
|
133
|
-
return acc;
|
|
134
|
-
}, {});
|
|
131
|
+
const dummyInputs = Object.fromEntries(inputVariables.map((v) => [v, "foo"]));
|
|
135
132
|
if (Array.isArray(template)) template.forEach((message) => {
|
|
136
133
|
if (message.type === "text" && "text" in message && typeof message.text === "string") renderTemplate(message.text, templateFormat, dummyInputs);
|
|
137
134
|
else if (message.type === "image_url") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"template.cjs","names":["template: string","nodes: ParsedTemplateNode[]","bracket: \"}\" | \"{\" | \"{}\"","start: number","i","template: mustache.TemplateSpans","context: string[]","values: InputValues","DEFAULT_FORMATTER_MAPPING: Record<TemplateFormat, Interpolator>","DEFAULT_PARSER_MAPPING: Record<TemplateFormat, Parser>","templateFormat: TemplateFormat","inputValues: InputValues","addLangChainErrorFields","template: MessageContent","inputVariables: string[]","dummyInputs: InputValues","e: any"],"sources":["../../src/prompts/template.ts"],"sourcesContent":["import mustache from \"mustache\";\nimport { MessageContent } from \"../messages/index.js\";\nimport type { InputValues } from \"../utils/types/index.js\";\nimport { addLangChainErrorFields } from \"../errors/index.js\";\n\nfunction configureMustache() {\n // Use unescaped HTML\n // https://github.com/janl/mustache.js?tab=readme-ov-file#variables\n mustache.escape = (text) => text;\n}\n\n/**\n * Type that specifies the format of a template.\n */\nexport type TemplateFormat = \"f-string\" | \"mustache\";\n\n/**\n * Type that represents a node in a parsed format string. It can be either\n * a literal text or a variable name.\n */\nexport type ParsedTemplateNode =\n | { type: \"literal\"; text: string }\n | { type: \"variable\"; name: string };\n\n/**\n * Alias for `ParsedTemplateNode` since it is the same for\n * both f-string and mustache templates.\n */\nexport type ParsedFStringNode = ParsedTemplateNode;\n\nexport const parseFString = (template: string): ParsedTemplateNode[] => {\n // Core logic replicated from internals of pythons built in Formatter class.\n // https://github.com/python/cpython/blob/135ec7cefbaffd516b77362ad2b2ad1025af462e/Objects/stringlib/unicode_format.h#L700-L706\n const chars = template.split(\"\");\n const nodes: ParsedTemplateNode[] = [];\n\n const nextBracket = (bracket: \"}\" | \"{\" | \"{}\", start: number) => {\n for (let i = start; i < chars.length; i += 1) {\n if (bracket.includes(chars[i])) {\n return i;\n }\n }\n return -1;\n };\n\n let i = 0;\n while (i < chars.length) {\n if (chars[i] === \"{\" && i + 1 < chars.length && chars[i + 1] === \"{\") {\n nodes.push({ type: \"literal\", text: \"{\" });\n i += 2;\n } else if (\n chars[i] === \"}\" &&\n i + 1 < chars.length &&\n chars[i + 1] === \"}\"\n ) {\n nodes.push({ type: \"literal\", text: \"}\" });\n i += 2;\n } else if (chars[i] === \"{\") {\n const j = nextBracket(\"}\", i);\n if (j < 0) {\n throw new Error(\"Unclosed '{' in template.\");\n }\n\n nodes.push({\n type: \"variable\",\n name: chars.slice(i + 1, j).join(\"\"),\n });\n i = j + 1;\n } else if (chars[i] === \"}\") {\n throw new Error(\"Single '}' in template.\");\n } else {\n const next = nextBracket(\"{}\", i);\n const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(\"\");\n nodes.push({ type: \"literal\", text });\n i = next < 0 ? chars.length : next;\n }\n }\n return nodes;\n};\n\n/**\n * Convert the result of mustache.parse into an array of ParsedTemplateNode,\n * to make it compatible with other LangChain string parsing template formats.\n *\n * @param {mustache.TemplateSpans} template The result of parsing a mustache template with the mustache.js library.\n * @param {string[]} context Array of section variable names for nested context\n * @returns {ParsedTemplateNode[]}\n */\nconst mustacheTemplateToNodes = (\n template: mustache.TemplateSpans,\n context: string[] = []\n): ParsedTemplateNode[] => {\n const nodes: ParsedTemplateNode[] = [];\n\n for (const temp of template) {\n if (temp[0] === \"name\") {\n const name = temp[1].includes(\".\") ? temp[1].split(\".\")[0] : temp[1];\n nodes.push({ type: \"variable\", name });\n } else if ([\"#\", \"&\", \"^\", \">\"].includes(temp[0])) {\n // # represents a section, \"&\" represents an unescaped variable.\n // These should both be considered variables.\n nodes.push({ type: \"variable\", name: temp[1] });\n\n // If this is a section with nested content, recursively process it\n if (temp[0] === \"#\" && temp.length > 4 && Array.isArray(temp[4])) {\n const newContext = [...context, temp[1]];\n const nestedNodes = mustacheTemplateToNodes(temp[4], newContext);\n nodes.push(...nestedNodes);\n }\n } else {\n nodes.push({ type: \"literal\", text: temp[1] });\n }\n }\n\n return nodes;\n};\n\nexport const parseMustache = (template: string) => {\n configureMustache();\n const parsed = mustache.parse(template);\n return mustacheTemplateToNodes(parsed);\n};\n\nexport const interpolateFString = (template: string, values: InputValues) => {\n return parseFString(template).reduce((res, node) => {\n if (node.type === \"variable\") {\n if (node.name in values) {\n const stringValue =\n typeof values[node.name] === \"string\"\n ? values[node.name]\n : JSON.stringify(values[node.name]);\n return res + stringValue;\n }\n throw new Error(`(f-string) Missing value for input ${node.name}`);\n }\n\n return res + node.text;\n }, \"\");\n};\n\nexport const interpolateMustache = (template: string, values: InputValues) => {\n configureMustache();\n return mustache.render(template, values);\n};\n\n/**\n * Type that represents a function that takes a template string and a set\n * of input values, and returns a string where all variables in the\n * template have been replaced with their corresponding values.\n */\ntype Interpolator = (template: string, values: InputValues) => string;\n\n/**\n * Type that represents a function that takes a template string and\n * returns an array of `ParsedTemplateNode`.\n */\ntype Parser = (template: string) => ParsedTemplateNode[];\n\nexport const DEFAULT_FORMATTER_MAPPING: Record<TemplateFormat, Interpolator> = {\n \"f-string\": interpolateFString,\n mustache: interpolateMustache,\n};\n\nexport const DEFAULT_PARSER_MAPPING: Record<TemplateFormat, Parser> = {\n \"f-string\": parseFString,\n mustache: parseMustache,\n};\n\nexport const renderTemplate = (\n template: string,\n templateFormat: TemplateFormat,\n inputValues: InputValues\n) => {\n try {\n return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues);\n } catch (e) {\n const error = addLangChainErrorFields(e, \"INVALID_PROMPT_INPUT\");\n throw error;\n }\n};\n\nexport const parseTemplate = (\n template: string,\n templateFormat: TemplateFormat\n) => DEFAULT_PARSER_MAPPING[templateFormat](template);\n\nexport const checkValidTemplate = (\n template: MessageContent,\n templateFormat: TemplateFormat,\n inputVariables: string[]\n) => {\n if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) {\n const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING);\n throw new Error(`Invalid template format. Got \\`${templateFormat}\\`;\n should be one of ${validFormats}`);\n }\n try {\n const dummyInputs: InputValues = inputVariables.reduce((acc, v) => {\n acc[v] = \"foo\";\n return acc;\n }, {} as Record<string, string>);\n if (Array.isArray(template)) {\n template.forEach((message) => {\n if (\n message.type === \"text\" &&\n \"text\" in message &&\n typeof message.text === \"string\"\n ) {\n renderTemplate(message.text, templateFormat, dummyInputs);\n } else if (message.type === \"image_url\") {\n if (typeof message.image_url === \"string\") {\n renderTemplate(message.image_url, templateFormat, dummyInputs);\n } else if (\n typeof message.image_url === \"object\" &&\n message.image_url !== null &&\n \"url\" in message.image_url &&\n typeof message.image_url.url === \"string\"\n ) {\n const imageUrl = message.image_url.url;\n renderTemplate(imageUrl, templateFormat, dummyInputs);\n }\n } else {\n throw new Error(\n `Invalid message template received. ${JSON.stringify(\n message,\n null,\n 2\n )}`\n );\n }\n });\n } else {\n renderTemplate(template, templateFormat, dummyInputs);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new Error(`Invalid prompt schema: ${e.message}`);\n }\n};\n"],"mappings":";;;;;AAKA,SAAS,oBAAoB;CAG3B,iBAAS,SAAS,CAAC,SAAS;AAC7B;AAqBD,MAAa,eAAe,CAACA,aAA2C;CAGtE,MAAM,QAAQ,SAAS,MAAM,GAAG;CAChC,MAAMC,QAA8B,CAAE;CAEtC,MAAM,cAAc,CAACC,SAA2BC,UAAkB;AAChE,OAAK,IAAIC,MAAI,OAAOA,MAAI,MAAM,QAAQA,OAAK,EACzC,KAAI,QAAQ,SAAS,MAAMA,KAAG,CAC5B,QAAOA;AAGX,SAAO;CACR;CAED,IAAI,IAAI;AACR,QAAO,IAAI,MAAM,OACf,KAAI,MAAM,OAAO,OAAO,IAAI,IAAI,MAAM,UAAU,MAAM,IAAI,OAAO,KAAK;EACpE,MAAM,KAAK;GAAE,MAAM;GAAW,MAAM;EAAK,EAAC;EAC1C,KAAK;CACN,WACC,MAAM,OAAO,OACb,IAAI,IAAI,MAAM,UACd,MAAM,IAAI,OAAO,KACjB;EACA,MAAM,KAAK;GAAE,MAAM;GAAW,MAAM;EAAK,EAAC;EAC1C,KAAK;CACN,WAAU,MAAM,OAAO,KAAK;EAC3B,MAAM,IAAI,YAAY,KAAK,EAAE;AAC7B,MAAI,IAAI,EACN,OAAM,IAAI,MAAM;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,UACjB,UAAU,WACV,OAAO,QAAQ,SAAS,UAExB,eAAe,QAAQ,MAAM,gBAAgB,YAAY;YAChD,QAAQ,SAAS,aAC1B;QAAI,OAAO,QAAQ,cAAc,UAC/B,eAAe,QAAQ,WAAW,gBAAgB,YAAY;aAE9D,OAAO,QAAQ,cAAc,YAC7B,QAAQ,cAAc,QACtB,SAAS,QAAQ,aACjB,OAAO,QAAQ,UAAU,QAAQ,UACjC;KACA,MAAM,WAAW,QAAQ,UAAU;KACnC,eAAe,UAAU,gBAAgB,YAAY;IACtD;SAED,OAAM,IAAI,MACR,CAAC,mCAAmC,EAAE,KAAK,UACzC,SACA,MACA,EACD,EAAE;EAGR,EAAC;OAEF,eAAe,UAAU,gBAAgB,YAAY;CAGxD,SAAQC,GAAQ;AACf,QAAM,IAAI,MAAM,CAAC,uBAAuB,EAAE,EAAE,SAAS;CACtD;AACF"}
|
|
1
|
+
{"version":3,"file":"template.cjs","names":["template: string","nodes: ParsedTemplateNode[]","bracket: \"}\" | \"{\" | \"{}\"","start: number","i","template: mustache.TemplateSpans","context: string[]","values: InputValues","DEFAULT_FORMATTER_MAPPING: Record<TemplateFormat, Interpolator>","DEFAULT_PARSER_MAPPING: Record<TemplateFormat, Parser>","templateFormat: TemplateFormat","inputValues: InputValues","addLangChainErrorFields","template: MessageContent","inputVariables: string[]","dummyInputs: InputValues","e: any"],"sources":["../../src/prompts/template.ts"],"sourcesContent":["import mustache from \"mustache\";\nimport { MessageContent } from \"../messages/index.js\";\nimport type { InputValues } from \"../utils/types/index.js\";\nimport { addLangChainErrorFields } from \"../errors/index.js\";\n\nfunction configureMustache() {\n // Use unescaped HTML\n // https://github.com/janl/mustache.js?tab=readme-ov-file#variables\n mustache.escape = (text) => text;\n}\n\n/**\n * Type that specifies the format of a template.\n */\nexport type TemplateFormat = \"f-string\" | \"mustache\";\n\n/**\n * Type that represents a node in a parsed format string. It can be either\n * a literal text or a variable name.\n */\nexport type ParsedTemplateNode =\n | { type: \"literal\"; text: string }\n | { type: \"variable\"; name: string };\n\n/**\n * Alias for `ParsedTemplateNode` since it is the same for\n * both f-string and mustache templates.\n */\nexport type ParsedFStringNode = ParsedTemplateNode;\n\nexport const parseFString = (template: string): ParsedTemplateNode[] => {\n // Core logic replicated from internals of pythons built in Formatter class.\n // https://github.com/python/cpython/blob/135ec7cefbaffd516b77362ad2b2ad1025af462e/Objects/stringlib/unicode_format.h#L700-L706\n const chars = template.split(\"\");\n const nodes: ParsedTemplateNode[] = [];\n\n const nextBracket = (bracket: \"}\" | \"{\" | \"{}\", start: number) => {\n for (let i = start; i < chars.length; i += 1) {\n if (bracket.includes(chars[i])) {\n return i;\n }\n }\n return -1;\n };\n\n let i = 0;\n while (i < chars.length) {\n if (chars[i] === \"{\" && i + 1 < chars.length && chars[i + 1] === \"{\") {\n nodes.push({ type: \"literal\", text: \"{\" });\n i += 2;\n } else if (\n chars[i] === \"}\" &&\n i + 1 < chars.length &&\n chars[i + 1] === \"}\"\n ) {\n nodes.push({ type: \"literal\", text: \"}\" });\n i += 2;\n } else if (chars[i] === \"{\") {\n const j = nextBracket(\"}\", i);\n if (j < 0) {\n throw new Error(\"Unclosed '{' in template.\");\n }\n\n nodes.push({\n type: \"variable\",\n name: chars.slice(i + 1, j).join(\"\"),\n });\n i = j + 1;\n } else if (chars[i] === \"}\") {\n throw new Error(\"Single '}' in template.\");\n } else {\n const next = nextBracket(\"{}\", i);\n const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(\"\");\n nodes.push({ type: \"literal\", text });\n i = next < 0 ? chars.length : next;\n }\n }\n return nodes;\n};\n\n/**\n * Convert the result of mustache.parse into an array of ParsedTemplateNode,\n * to make it compatible with other LangChain string parsing template formats.\n *\n * @param {mustache.TemplateSpans} template The result of parsing a mustache template with the mustache.js library.\n * @param {string[]} context Array of section variable names for nested context\n * @returns {ParsedTemplateNode[]}\n */\nconst mustacheTemplateToNodes = (\n template: mustache.TemplateSpans,\n context: string[] = []\n): ParsedTemplateNode[] => {\n const nodes: ParsedTemplateNode[] = [];\n\n for (const temp of template) {\n if (temp[0] === \"name\") {\n const name = temp[1].includes(\".\") ? temp[1].split(\".\")[0] : temp[1];\n nodes.push({ type: \"variable\", name });\n } else if ([\"#\", \"&\", \"^\", \">\"].includes(temp[0])) {\n // # represents a section, \"&\" represents an unescaped variable.\n // These should both be considered variables.\n nodes.push({ type: \"variable\", name: temp[1] });\n\n // If this is a section with nested content, recursively process it\n if (temp[0] === \"#\" && temp.length > 4 && Array.isArray(temp[4])) {\n const newContext = [...context, temp[1]];\n const nestedNodes = mustacheTemplateToNodes(temp[4], newContext);\n nodes.push(...nestedNodes);\n }\n } else {\n nodes.push({ type: \"literal\", text: temp[1] });\n }\n }\n\n return nodes;\n};\n\nexport const parseMustache = (template: string) => {\n configureMustache();\n const parsed = mustache.parse(template);\n return mustacheTemplateToNodes(parsed);\n};\n\nexport const interpolateFString = (template: string, values: InputValues) => {\n return parseFString(template).reduce((res, node) => {\n if (node.type === \"variable\") {\n if (node.name in values) {\n const stringValue =\n typeof values[node.name] === \"string\"\n ? values[node.name]\n : JSON.stringify(values[node.name]);\n return res + stringValue;\n }\n throw new Error(`(f-string) Missing value for input ${node.name}`);\n }\n\n return res + node.text;\n }, \"\");\n};\n\nexport const interpolateMustache = (template: string, values: InputValues) => {\n configureMustache();\n return mustache.render(template, values);\n};\n\n/**\n * Type that represents a function that takes a template string and a set\n * of input values, and returns a string where all variables in the\n * template have been replaced with their corresponding values.\n */\ntype Interpolator = (template: string, values: InputValues) => string;\n\n/**\n * Type that represents a function that takes a template string and\n * returns an array of `ParsedTemplateNode`.\n */\ntype Parser = (template: string) => ParsedTemplateNode[];\n\nexport const DEFAULT_FORMATTER_MAPPING: Record<TemplateFormat, Interpolator> = {\n \"f-string\": interpolateFString,\n mustache: interpolateMustache,\n};\n\nexport const DEFAULT_PARSER_MAPPING: Record<TemplateFormat, Parser> = {\n \"f-string\": parseFString,\n mustache: parseMustache,\n};\n\nexport const renderTemplate = (\n template: string,\n templateFormat: TemplateFormat,\n inputValues: InputValues\n) => {\n try {\n return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues);\n } catch (e) {\n const error = addLangChainErrorFields(e, \"INVALID_PROMPT_INPUT\");\n throw error;\n }\n};\n\nexport const parseTemplate = (\n template: string,\n templateFormat: TemplateFormat\n) => DEFAULT_PARSER_MAPPING[templateFormat](template);\n\nexport const checkValidTemplate = (\n template: MessageContent,\n templateFormat: TemplateFormat,\n inputVariables: string[]\n) => {\n if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) {\n const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING);\n throw new Error(`Invalid template format. Got \\`${templateFormat}\\`;\n should be one of ${validFormats}`);\n }\n try {\n // Build dummy inputs using Object.fromEntries to avoid prototype pollution\n // from dynamic property assignment with user-provided keys\n const dummyInputs: InputValues = Object.fromEntries(\n inputVariables.map((v) => [v, \"foo\"])\n );\n if (Array.isArray(template)) {\n template.forEach((message) => {\n if (\n message.type === \"text\" &&\n \"text\" in message &&\n typeof message.text === \"string\"\n ) {\n renderTemplate(message.text, templateFormat, dummyInputs);\n } else if (message.type === \"image_url\") {\n if (typeof message.image_url === \"string\") {\n renderTemplate(message.image_url, templateFormat, dummyInputs);\n } else if (\n typeof message.image_url === \"object\" &&\n message.image_url !== null &&\n \"url\" in message.image_url &&\n typeof message.image_url.url === \"string\"\n ) {\n const imageUrl = message.image_url.url;\n renderTemplate(imageUrl, templateFormat, dummyInputs);\n }\n } else {\n throw new Error(\n `Invalid message template received. ${JSON.stringify(\n message,\n null,\n 2\n )}`\n );\n }\n });\n } else {\n renderTemplate(template, templateFormat, dummyInputs);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new Error(`Invalid prompt schema: ${e.message}`);\n }\n};\n"],"mappings":";;;;;AAKA,SAAS,oBAAoB;CAG3B,iBAAS,SAAS,CAAC,SAAS;AAC7B;AAqBD,MAAa,eAAe,CAACA,aAA2C;C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127,10 +127,7 @@ const checkValidTemplate = (template, templateFormat, inputVariables) => {
|
|
|
127
127
|
should be one of ${validFormats}`);
|
|
128
128
|
}
|
|
129
129
|
try {
|
|
130
|
-
const dummyInputs = inputVariables.
|
|
131
|
-
acc[v] = "foo";
|
|
132
|
-
return acc;
|
|
133
|
-
}, {});
|
|
130
|
+
const dummyInputs = Object.fromEntries(inputVariables.map((v) => [v, "foo"]));
|
|
134
131
|
if (Array.isArray(template)) template.forEach((message) => {
|
|
135
132
|
if (message.type === "text" && "text" in message && typeof message.text === "string") renderTemplate(message.text, templateFormat, dummyInputs);
|
|
136
133
|
else if (message.type === "image_url") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"template.js","names":["template: string","nodes: ParsedTemplateNode[]","bracket: \"}\" | \"{\" | \"{}\"","start: number","i","template: mustache.TemplateSpans","context: string[]","values: InputValues","DEFAULT_FORMATTER_MAPPING: Record<TemplateFormat, Interpolator>","DEFAULT_PARSER_MAPPING: Record<TemplateFormat, Parser>","templateFormat: TemplateFormat","inputValues: InputValues","template: MessageContent","inputVariables: string[]","dummyInputs: InputValues","e: any"],"sources":["../../src/prompts/template.ts"],"sourcesContent":["import mustache from \"mustache\";\nimport { MessageContent } from \"../messages/index.js\";\nimport type { InputValues } from \"../utils/types/index.js\";\nimport { addLangChainErrorFields } from \"../errors/index.js\";\n\nfunction configureMustache() {\n // Use unescaped HTML\n // https://github.com/janl/mustache.js?tab=readme-ov-file#variables\n mustache.escape = (text) => text;\n}\n\n/**\n * Type that specifies the format of a template.\n */\nexport type TemplateFormat = \"f-string\" | \"mustache\";\n\n/**\n * Type that represents a node in a parsed format string. It can be either\n * a literal text or a variable name.\n */\nexport type ParsedTemplateNode =\n | { type: \"literal\"; text: string }\n | { type: \"variable\"; name: string };\n\n/**\n * Alias for `ParsedTemplateNode` since it is the same for\n * both f-string and mustache templates.\n */\nexport type ParsedFStringNode = ParsedTemplateNode;\n\nexport const parseFString = (template: string): ParsedTemplateNode[] => {\n // Core logic replicated from internals of pythons built in Formatter class.\n // https://github.com/python/cpython/blob/135ec7cefbaffd516b77362ad2b2ad1025af462e/Objects/stringlib/unicode_format.h#L700-L706\n const chars = template.split(\"\");\n const nodes: ParsedTemplateNode[] = [];\n\n const nextBracket = (bracket: \"}\" | \"{\" | \"{}\", start: number) => {\n for (let i = start; i < chars.length; i += 1) {\n if (bracket.includes(chars[i])) {\n return i;\n }\n }\n return -1;\n };\n\n let i = 0;\n while (i < chars.length) {\n if (chars[i] === \"{\" && i + 1 < chars.length && chars[i + 1] === \"{\") {\n nodes.push({ type: \"literal\", text: \"{\" });\n i += 2;\n } else if (\n chars[i] === \"}\" &&\n i + 1 < chars.length &&\n chars[i + 1] === \"}\"\n ) {\n nodes.push({ type: \"literal\", text: \"}\" });\n i += 2;\n } else if (chars[i] === \"{\") {\n const j = nextBracket(\"}\", i);\n if (j < 0) {\n throw new Error(\"Unclosed '{' in template.\");\n }\n\n nodes.push({\n type: \"variable\",\n name: chars.slice(i + 1, j).join(\"\"),\n });\n i = j + 1;\n } else if (chars[i] === \"}\") {\n throw new Error(\"Single '}' in template.\");\n } else {\n const next = nextBracket(\"{}\", i);\n const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(\"\");\n nodes.push({ type: \"literal\", text });\n i = next < 0 ? chars.length : next;\n }\n }\n return nodes;\n};\n\n/**\n * Convert the result of mustache.parse into an array of ParsedTemplateNode,\n * to make it compatible with other LangChain string parsing template formats.\n *\n * @param {mustache.TemplateSpans} template The result of parsing a mustache template with the mustache.js library.\n * @param {string[]} context Array of section variable names for nested context\n * @returns {ParsedTemplateNode[]}\n */\nconst mustacheTemplateToNodes = (\n template: mustache.TemplateSpans,\n context: string[] = []\n): ParsedTemplateNode[] => {\n const nodes: ParsedTemplateNode[] = [];\n\n for (const temp of template) {\n if (temp[0] === \"name\") {\n const name = temp[1].includes(\".\") ? temp[1].split(\".\")[0] : temp[1];\n nodes.push({ type: \"variable\", name });\n } else if ([\"#\", \"&\", \"^\", \">\"].includes(temp[0])) {\n // # represents a section, \"&\" represents an unescaped variable.\n // These should both be considered variables.\n nodes.push({ type: \"variable\", name: temp[1] });\n\n // If this is a section with nested content, recursively process it\n if (temp[0] === \"#\" && temp.length > 4 && Array.isArray(temp[4])) {\n const newContext = [...context, temp[1]];\n const nestedNodes = mustacheTemplateToNodes(temp[4], newContext);\n nodes.push(...nestedNodes);\n }\n } else {\n nodes.push({ type: \"literal\", text: temp[1] });\n }\n }\n\n return nodes;\n};\n\nexport const parseMustache = (template: string) => {\n configureMustache();\n const parsed = mustache.parse(template);\n return mustacheTemplateToNodes(parsed);\n};\n\nexport const interpolateFString = (template: string, values: InputValues) => {\n return parseFString(template).reduce((res, node) => {\n if (node.type === \"variable\") {\n if (node.name in values) {\n const stringValue =\n typeof values[node.name] === \"string\"\n ? values[node.name]\n : JSON.stringify(values[node.name]);\n return res + stringValue;\n }\n throw new Error(`(f-string) Missing value for input ${node.name}`);\n }\n\n return res + node.text;\n }, \"\");\n};\n\nexport const interpolateMustache = (template: string, values: InputValues) => {\n configureMustache();\n return mustache.render(template, values);\n};\n\n/**\n * Type that represents a function that takes a template string and a set\n * of input values, and returns a string where all variables in the\n * template have been replaced with their corresponding values.\n */\ntype Interpolator = (template: string, values: InputValues) => string;\n\n/**\n * Type that represents a function that takes a template string and\n * returns an array of `ParsedTemplateNode`.\n */\ntype Parser = (template: string) => ParsedTemplateNode[];\n\nexport const DEFAULT_FORMATTER_MAPPING: Record<TemplateFormat, Interpolator> = {\n \"f-string\": interpolateFString,\n mustache: interpolateMustache,\n};\n\nexport const DEFAULT_PARSER_MAPPING: Record<TemplateFormat, Parser> = {\n \"f-string\": parseFString,\n mustache: parseMustache,\n};\n\nexport const renderTemplate = (\n template: string,\n templateFormat: TemplateFormat,\n inputValues: InputValues\n) => {\n try {\n return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues);\n } catch (e) {\n const error = addLangChainErrorFields(e, \"INVALID_PROMPT_INPUT\");\n throw error;\n }\n};\n\nexport const parseTemplate = (\n template: string,\n templateFormat: TemplateFormat\n) => DEFAULT_PARSER_MAPPING[templateFormat](template);\n\nexport const checkValidTemplate = (\n template: MessageContent,\n templateFormat: TemplateFormat,\n inputVariables: string[]\n) => {\n if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) {\n const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING);\n throw new Error(`Invalid template format. Got \\`${templateFormat}\\`;\n should be one of ${validFormats}`);\n }\n try {\n const dummyInputs: InputValues = inputVariables.reduce((acc, v) => {\n acc[v] = \"foo\";\n return acc;\n }, {} as Record<string, string>);\n if (Array.isArray(template)) {\n template.forEach((message) => {\n if (\n message.type === \"text\" &&\n \"text\" in message &&\n typeof message.text === \"string\"\n ) {\n renderTemplate(message.text, templateFormat, dummyInputs);\n } else if (message.type === \"image_url\") {\n if (typeof message.image_url === \"string\") {\n renderTemplate(message.image_url, templateFormat, dummyInputs);\n } else if (\n typeof message.image_url === \"object\" &&\n message.image_url !== null &&\n \"url\" in message.image_url &&\n typeof message.image_url.url === \"string\"\n ) {\n const imageUrl = message.image_url.url;\n renderTemplate(imageUrl, templateFormat, dummyInputs);\n }\n } else {\n throw new Error(\n `Invalid message template received. ${JSON.stringify(\n message,\n null,\n 2\n )}`\n );\n }\n });\n } else {\n renderTemplate(template, templateFormat, dummyInputs);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new Error(`Invalid prompt schema: ${e.message}`);\n }\n};\n"],"mappings":";;;;AAKA,SAAS,oBAAoB;CAG3B,SAAS,SAAS,CAAC,SAAS;AAC7B;AAqBD,MAAa,eAAe,CAACA,aAA2C;CAGtE,MAAM,QAAQ,SAAS,MAAM,GAAG;CAChC,MAAMC,QAA8B,CAAE;CAEtC,MAAM,cAAc,CAACC,SAA2BC,UAAkB;AAChE,OAAK,IAAIC,MAAI,OAAOA,MAAI,MAAM,QAAQA,OAAK,EACzC,KAAI,QAAQ,SAAS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AAM;CACP;AACF;AAED,MAAa,gBAAgB,CAC3BX,UACAU,mBACG,uBAAuB,gBAAgB,SAAS;AAErD,MAAa,qBAAqB,CAChCE,UACAF,gBACAG,mBACG;AACH,KAAI,EAAE,kBAAkB,4BAA4B;EAClD,MAAM,eAAe,OAAO,KAAK,0BAA0B;AAC3D,QAAM,IAAI,MAAM,CAAC,+BAA+B,EAAE,eAAe;0CAC3B,EAAE,cAAc;CACvD;AACD,KAAI;EACF,MAAMC,cAA2B,eAAe,OAAO,CAAC,KAAK,MAAM;GACjE,IAAI,KAAK;AACT,UAAO;EACR,GAAE,CAAE,EAA2B;AAChC,MAAI,MAAM,QAAQ,SAAS,EACzB,SAAS,QAAQ,CAAC,YAAY;AAC5B,OACE,QAAQ,SAAS,UACjB,UAAU,WACV,OAAO,QAAQ,SAAS,UAExB,eAAe,QAAQ,MAAM,gBAAgB,YAAY;YAChD,QAAQ,SAAS,aAC1B;QAAI,OAAO,QAAQ,cAAc,UAC/B,eAAe,QAAQ,WAAW,gBAAgB,YAAY;aAE9D,OAAO,QAAQ,cAAc,YAC7B,QAAQ,cAAc,QACtB,SAAS,QAAQ,aACjB,OAAO,QAAQ,UAAU,QAAQ,UACjC;KACA,MAAM,WAAW,QAAQ,UAAU;KACnC,eAAe,UAAU,gBAAgB,YAAY;IACtD;SAED,OAAM,IAAI,MACR,CAAC,mCAAmC,EAAE,KAAK,UACzC,SACA,MACA,EACD,EAAE;EAGR,EAAC;OAEF,eAAe,UAAU,gBAAgB,YAAY;CAGxD,SAAQC,GAAQ;AACf,QAAM,IAAI,MAAM,CAAC,uBAAuB,EAAE,EAAE,SAAS;CACtD;AACF"}
|
|
1
|
+
{"version":3,"file":"template.js","names":["template: string","nodes: ParsedTemplateNode[]","bracket: \"}\" | \"{\" | \"{}\"","start: number","i","template: mustache.TemplateSpans","context: string[]","values: InputValues","DEFAULT_FORMATTER_MAPPING: Record<TemplateFormat, Interpolator>","DEFAULT_PARSER_MAPPING: Record<TemplateFormat, Parser>","templateFormat: TemplateFormat","inputValues: InputValues","template: MessageContent","inputVariables: string[]","dummyInputs: InputValues","e: any"],"sources":["../../src/prompts/template.ts"],"sourcesContent":["import mustache from \"mustache\";\nimport { MessageContent } from \"../messages/index.js\";\nimport type { InputValues } from \"../utils/types/index.js\";\nimport { addLangChainErrorFields } from \"../errors/index.js\";\n\nfunction configureMustache() {\n // Use unescaped HTML\n // https://github.com/janl/mustache.js?tab=readme-ov-file#variables\n mustache.escape = (text) => text;\n}\n\n/**\n * Type that specifies the format of a template.\n */\nexport type TemplateFormat = \"f-string\" | \"mustache\";\n\n/**\n * Type that represents a node in a parsed format string. It can be either\n * a literal text or a variable name.\n */\nexport type ParsedTemplateNode =\n | { type: \"literal\"; text: string }\n | { type: \"variable\"; name: string };\n\n/**\n * Alias for `ParsedTemplateNode` since it is the same for\n * both f-string and mustache templates.\n */\nexport type ParsedFStringNode = ParsedTemplateNode;\n\nexport const parseFString = (template: string): ParsedTemplateNode[] => {\n // Core logic replicated from internals of pythons built in Formatter class.\n // https://github.com/python/cpython/blob/135ec7cefbaffd516b77362ad2b2ad1025af462e/Objects/stringlib/unicode_format.h#L700-L706\n const chars = template.split(\"\");\n const nodes: ParsedTemplateNode[] = [];\n\n const nextBracket = (bracket: \"}\" | \"{\" | \"{}\", start: number) => {\n for (let i = start; i < chars.length; i += 1) {\n if (bracket.includes(chars[i])) {\n return i;\n }\n }\n return -1;\n };\n\n let i = 0;\n while (i < chars.length) {\n if (chars[i] === \"{\" && i + 1 < chars.length && chars[i + 1] === \"{\") {\n nodes.push({ type: \"literal\", text: \"{\" });\n i += 2;\n } else if (\n chars[i] === \"}\" &&\n i + 1 < chars.length &&\n chars[i + 1] === \"}\"\n ) {\n nodes.push({ type: \"literal\", text: \"}\" });\n i += 2;\n } else if (chars[i] === \"{\") {\n const j = nextBracket(\"}\", i);\n if (j < 0) {\n throw new Error(\"Unclosed '{' in template.\");\n }\n\n nodes.push({\n type: \"variable\",\n name: chars.slice(i + 1, j).join(\"\"),\n });\n i = j + 1;\n } else if (chars[i] === \"}\") {\n throw new Error(\"Single '}' in template.\");\n } else {\n const next = nextBracket(\"{}\", i);\n const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(\"\");\n nodes.push({ type: \"literal\", text });\n i = next < 0 ? chars.length : next;\n }\n }\n return nodes;\n};\n\n/**\n * Convert the result of mustache.parse into an array of ParsedTemplateNode,\n * to make it compatible with other LangChain string parsing template formats.\n *\n * @param {mustache.TemplateSpans} template The result of parsing a mustache template with the mustache.js library.\n * @param {string[]} context Array of section variable names for nested context\n * @returns {ParsedTemplateNode[]}\n */\nconst mustacheTemplateToNodes = (\n template: mustache.TemplateSpans,\n context: string[] = []\n): ParsedTemplateNode[] => {\n const nodes: ParsedTemplateNode[] = [];\n\n for (const temp of template) {\n if (temp[0] === \"name\") {\n const name = temp[1].includes(\".\") ? temp[1].split(\".\")[0] : temp[1];\n nodes.push({ type: \"variable\", name });\n } else if ([\"#\", \"&\", \"^\", \">\"].includes(temp[0])) {\n // # represents a section, \"&\" represents an unescaped variable.\n // These should both be considered variables.\n nodes.push({ type: \"variable\", name: temp[1] });\n\n // If this is a section with nested content, recursively process it\n if (temp[0] === \"#\" && temp.length > 4 && Array.isArray(temp[4])) {\n const newContext = [...context, temp[1]];\n const nestedNodes = mustacheTemplateToNodes(temp[4], newContext);\n nodes.push(...nestedNodes);\n }\n } else {\n nodes.push({ type: \"literal\", text: temp[1] });\n }\n }\n\n return nodes;\n};\n\nexport const parseMustache = (template: string) => {\n configureMustache();\n const parsed = mustache.parse(template);\n return mustacheTemplateToNodes(parsed);\n};\n\nexport const interpolateFString = (template: string, values: InputValues) => {\n return parseFString(template).reduce((res, node) => {\n if (node.type === \"variable\") {\n if (node.name in values) {\n const stringValue =\n typeof values[node.name] === \"string\"\n ? values[node.name]\n : JSON.stringify(values[node.name]);\n return res + stringValue;\n }\n throw new Error(`(f-string) Missing value for input ${node.name}`);\n }\n\n return res + node.text;\n }, \"\");\n};\n\nexport const interpolateMustache = (template: string, values: InputValues) => {\n configureMustache();\n return mustache.render(template, values);\n};\n\n/**\n * Type that represents a function that takes a template string and a set\n * of input values, and returns a string where all variables in the\n * template have been replaced with their corresponding values.\n */\ntype Interpolator = (template: string, values: InputValues) => string;\n\n/**\n * Type that represents a function that takes a template string and\n * returns an array of `ParsedTemplateNode`.\n */\ntype Parser = (template: string) => ParsedTemplateNode[];\n\nexport const DEFAULT_FORMATTER_MAPPING: Record<TemplateFormat, Interpolator> = {\n \"f-string\": interpolateFString,\n mustache: interpolateMustache,\n};\n\nexport const DEFAULT_PARSER_MAPPING: Record<TemplateFormat, Parser> = {\n \"f-string\": parseFString,\n mustache: parseMustache,\n};\n\nexport const renderTemplate = (\n template: string,\n templateFormat: TemplateFormat,\n inputValues: InputValues\n) => {\n try {\n return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues);\n } catch (e) {\n const error = addLangChainErrorFields(e, \"INVALID_PROMPT_INPUT\");\n throw error;\n }\n};\n\nexport const parseTemplate = (\n template: string,\n templateFormat: TemplateFormat\n) => DEFAULT_PARSER_MAPPING[templateFormat](template);\n\nexport const checkValidTemplate = (\n template: MessageContent,\n templateFormat: TemplateFormat,\n inputVariables: string[]\n) => {\n if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) {\n const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING);\n throw new Error(`Invalid template format. Got \\`${templateFormat}\\`;\n should be one of ${validFormats}`);\n }\n try {\n // Build dummy inputs using Object.fromEntries to avoid prototype pollution\n // from dynamic property assignment with user-provided keys\n const dummyInputs: InputValues = Object.fromEntries(\n inputVariables.map((v) => [v, \"foo\"])\n );\n if (Array.isArray(template)) {\n template.forEach((message) => {\n if (\n message.type === \"text\" &&\n \"text\" in message &&\n typeof message.text === \"string\"\n ) {\n renderTemplate(message.text, templateFormat, dummyInputs);\n } else if (message.type === \"image_url\") {\n if (typeof message.image_url === \"string\") {\n renderTemplate(message.image_url, templateFormat, dummyInputs);\n } else if (\n typeof message.image_url === \"object\" &&\n message.image_url !== null &&\n \"url\" in message.image_url &&\n typeof message.image_url.url === \"string\"\n ) {\n const imageUrl = message.image_url.url;\n renderTemplate(imageUrl, templateFormat, dummyInputs);\n }\n } else {\n throw new Error(\n `Invalid message template received. ${JSON.stringify(\n message,\n null,\n 2\n )}`\n );\n }\n });\n } else {\n renderTemplate(template, templateFormat, dummyInputs);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new Error(`Invalid prompt schema: ${e.message}`);\n }\n};\n"],"mappings":";;;;AAKA,SAAS,oBAAoB;CAG3B,SAAS,SAAS,CAAC,SAAS;AAC7B;AAqBD,MAAa,eAAe,CAACA,aAA2C;CAGtE,MAAM,QAAQ,SAAS,MAAM,GAAG;CAChC,MAAMC,QAA8B,CAAE;CAEtC,MAAM,cAAc,CAACC,SAA2BC,UAAkB;AAChE,OAAK,IAAIC,MAAI,OAAOA,MAAI,MAAM,QAAQA,OAAK,EACzC,KAAI,QAAQ,SAAS,MAAMA,KAAG,CAC5B,QAAOA;AAGX,SAAO;CACR;CAED,IAAI,IAAI;AACR,QAAO,IAAI,MAAM,OACf,KAAI,MAAM,OAAO,OAAO,IAAI,IAAI,MAAM,UAAU,MAAM,IAAI,OAAO,KAAK;EACpE,MAAM,KAAK;GAAE,MAAM;GAAW,MAAM;EAAK,EAAC;EAC1C,KAAK;CACN,WACC,MAAM,OAAO,OACb,IAAI,IAAI,MAAM,UACd,MAAM,IAAI,OAAO,KACjB;EACA,MAAM,KAAK;GAAE,MAAM;GAAW,MAAM;EAAK,EAAC;EAC1C,KAAK;CACN,WAAU,MAAM,OAAO,KAAK;EAC3B,MAAM,IAAI,YAAY,KAAK,EAAE;AAC7B,MAAI,IAAI,EACN,OAAM,IAAI,MAAM;EAGlB,MAAM,KAAK;GACT,MAAM;GACN,MAAM,MAAM,MAAM,IAAI,GAAG,EAAE,CAAC,KAAK,GAAG;EACrC,EAAC;EACF,IAAI,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/B,eAAe,QAAQ,WAAW,gBAAgB,YAAY;aAE9D,OAAO,QAAQ,cAAc,YAC7B,QAAQ,cAAc,QACtB,SAAS,QAAQ,aACjB,OAAO,QAAQ,UAAU,QAAQ,UACjC;KACA,MAAM,WAAW,QAAQ,UAAU;KACnC,eAAe,UAAU,gBAAgB,YAAY;IACtD;SAED,OAAM,IAAI,MACR,CAAC,mCAAmC,EAAE,KAAK,UACzC,SACA,MACA,EACD,EAAE;EAGR,EAAC;OAEF,eAAe,UAAU,gBAAgB,YAAY;CAGxD,SAAQC,GAAQ;AACf,QAAM,IAAI,MAAM,CAAC,uBAAuB,EAAE,EAAE,SAAS;CACtD;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["Runnable","fields?: BaseRetrieverInput","_query: string","_callbacks?: CallbackManagerForRetrieverRun","input: string","options?: RunnableConfig","ensureConfig","parseCallbackConfigArg","CallbackManager"],"sources":["../../src/retrievers/index.ts"],"sourcesContent":["import {\n CallbackManager,\n CallbackManagerForRetrieverRun,\n Callbacks,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport type { DocumentInterface } from \"../documents/document.js\";\nimport { Runnable, type RunnableInterface } from \"../runnables/base.js\";\nimport { RunnableConfig, ensureConfig } from \"../runnables/config.js\";\n\n/**\n * Input configuration options for initializing a retriever that extends\n * the `BaseRetriever` class. This interface provides base properties\n * common to all retrievers, allowing customization of callback functions,\n * tagging, metadata, and logging verbosity.\n *\n * Fields:\n * - `callbacks` (optional): An array of callback functions that handle various\n * events during retrieval, such as logging, error handling, or progress updates.\n *\n * - `tags` (optional): An array of strings used to add contextual tags to\n * retrieval operations, allowing for easier categorization and tracking.\n *\n * - `metadata` (optional): A record of key-value pairs to store additional\n * contextual information for retrieval operations, which can be useful\n * for logging or auditing purposes.\n *\n * - `verbose` (optional): A boolean flag that, if set to `true`, enables\n * detailed logging and output during the retrieval process. Defaults to `false`.\n */\nexport interface BaseRetrieverInput {\n callbacks?: Callbacks;\n tags?: string[];\n metadata?: Record<string, unknown>;\n verbose?: boolean;\n}\n\n/**\n * Interface for a base retriever that defines core functionality for\n * retrieving relevant documents from a source based on a query.\n *\n * The `BaseRetrieverInterface` standardizes the `getRelevantDocuments` method,\n * enabling retrieval of documents that match the query criteria.\n *\n * @template Metadata - The type of metadata associated with each document,\n * defaulting to `Record<string, any>`.\n */\nexport interface BaseRetrieverInterface<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Metadata extends Record<string, any> = Record<string, any
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["Runnable","fields?: BaseRetrieverInput","_query: string","_callbacks?: CallbackManagerForRetrieverRun","input: string","options?: RunnableConfig","ensureConfig","parseCallbackConfigArg","CallbackManager"],"sources":["../../src/retrievers/index.ts"],"sourcesContent":["import {\n CallbackManager,\n CallbackManagerForRetrieverRun,\n Callbacks,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport type { DocumentInterface } from \"../documents/document.js\";\nimport { Runnable, type RunnableInterface } from \"../runnables/base.js\";\nimport { RunnableConfig, ensureConfig } from \"../runnables/config.js\";\n\n/**\n * Input configuration options for initializing a retriever that extends\n * the `BaseRetriever` class. This interface provides base properties\n * common to all retrievers, allowing customization of callback functions,\n * tagging, metadata, and logging verbosity.\n *\n * Fields:\n * - `callbacks` (optional): An array of callback functions that handle various\n * events during retrieval, such as logging, error handling, or progress updates.\n *\n * - `tags` (optional): An array of strings used to add contextual tags to\n * retrieval operations, allowing for easier categorization and tracking.\n *\n * - `metadata` (optional): A record of key-value pairs to store additional\n * contextual information for retrieval operations, which can be useful\n * for logging or auditing purposes.\n *\n * - `verbose` (optional): A boolean flag that, if set to `true`, enables\n * detailed logging and output during the retrieval process. Defaults to `false`.\n */\nexport interface BaseRetrieverInput {\n callbacks?: Callbacks;\n tags?: string[];\n metadata?: Record<string, unknown>;\n verbose?: boolean;\n}\n\n/**\n * Interface for a base retriever that defines core functionality for\n * retrieving relevant documents from a source based on a query.\n *\n * The `BaseRetrieverInterface` standardizes the `getRelevantDocuments` method,\n * enabling retrieval of documents that match the query criteria.\n *\n * @template Metadata - The type of metadata associated with each document,\n * defaulting to `Record<string, any>`.\n */\nexport interface BaseRetrieverInterface<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Metadata extends Record<string, any> = Record<string, any>,\n> extends RunnableInterface<string, DocumentInterface<Metadata>[]> {}\n\n/**\n * Abstract base class for a document retrieval system, designed to\n * process string queries and return the most relevant documents from a source.\n *\n * `BaseRetriever` provides common properties and methods for derived retrievers,\n * such as callbacks, tagging, and verbose logging. Custom retrieval systems\n * should extend this class and implement `_getRelevantDocuments` to define\n * the specific retrieval logic.\n *\n * @template Metadata - The type of metadata associated with each document,\n * defaulting to `Record<string, any>`.\n */\nexport abstract class BaseRetriever<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Metadata extends Record<string, any> = Record<string, any>,\n >\n extends Runnable<string, DocumentInterface<Metadata>[]>\n implements BaseRetrieverInterface\n{\n /**\n * Optional callbacks to handle various events in the retrieval process.\n */\n callbacks?: Callbacks;\n\n /**\n * Tags to label or categorize the retrieval operation.\n */\n tags?: string[];\n\n /**\n * Metadata to provide additional context or information about the retrieval\n * operation.\n */\n metadata?: Record<string, unknown>;\n\n /**\n * If set to `true`, enables verbose logging for the retrieval process.\n */\n verbose?: boolean;\n\n /**\n * Constructs a new `BaseRetriever` instance with optional configuration fields.\n *\n * @param fields - Optional input configuration that can include `callbacks`,\n * `tags`, `metadata`, and `verbose` settings for custom retriever behavior.\n */\n constructor(fields?: BaseRetrieverInput) {\n super(fields);\n this.callbacks = fields?.callbacks;\n this.tags = fields?.tags ?? [];\n this.metadata = fields?.metadata ?? {};\n this.verbose = fields?.verbose ?? false;\n }\n\n /**\n * TODO: This should be an abstract method, but we'd like to avoid breaking\n * changes to people currently using subclassed custom retrievers.\n * Change it on next major release.\n */\n /**\n * Placeholder method for retrieving relevant documents based on a query.\n *\n * This method is intended to be implemented by subclasses and will be\n * converted to an abstract method in the next major release. Currently, it\n * throws an error if not implemented, ensuring that custom retrievers define\n * the specific retrieval logic.\n *\n * @param _query - The query string used to search for relevant documents.\n * @param _callbacks - (optional) Callback manager for managing callbacks\n * during retrieval.\n * @returns A promise resolving to an array of `DocumentInterface` instances relevant to the query.\n * @throws {Error} Throws an error indicating the method is not implemented.\n */\n _getRelevantDocuments(\n _query: string,\n _callbacks?: CallbackManagerForRetrieverRun\n ): Promise<DocumentInterface<Metadata>[]> {\n throw new Error(\"Not implemented!\");\n }\n\n /**\n * Executes a retrieval operation.\n *\n * @param input - The query string used to search for relevant documents.\n * @param options - (optional) Configuration options for the retrieval run,\n * which may include callbacks, tags, and metadata.\n * @returns A promise that resolves to an array of `DocumentInterface` instances\n * representing the most relevant documents to the query.\n */\n async invoke(\n input: string,\n options?: RunnableConfig\n ): Promise<DocumentInterface<Metadata>[]> {\n const parsedConfig = ensureConfig(parseCallbackConfigArg(options));\n const callbackManager_ = await CallbackManager.configure(\n parsedConfig.callbacks,\n this.callbacks,\n parsedConfig.tags,\n this.tags,\n parsedConfig.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const runManager = await callbackManager_?.handleRetrieverStart(\n this.toJSON(),\n input,\n parsedConfig.runId,\n undefined,\n undefined,\n undefined,\n parsedConfig.runName\n );\n try {\n const results = await this._getRelevantDocuments(input, runManager);\n await runManager?.handleRetrieverEnd(results);\n return results;\n } catch (error) {\n await runManager?.handleRetrieverError(error);\n throw error;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgEA,IAAsB,gBAAtB,cAIUA,sBAEV;;;;CAIE;;;;CAKA;;;;;CAMA;;;;CAKA;;;;;;;CAQA,YAAYC,QAA6B;EACvC,MAAM,OAAO;EACb,KAAK,YAAY,QAAQ;EACzB,KAAK,OAAO,QAAQ,QAAQ,CAAE;EAC9B,KAAK,WAAW,QAAQ,YAAY,CAAE;EACtC,KAAK,UAAU,QAAQ,WAAW;CACnC;;;;;;;;;;;;;;;;;;;;CAqBD,sBACEC,QACAC,YACwC;AACxC,QAAM,IAAI,MAAM;CACjB;;;;;;;;;;CAWD,MAAM,OACJC,OACAC,SACwC;EACxC,MAAM,eAAeC,4BAAaC,iDAAuB,QAAQ,CAAC;EAClE,MAAM,mBAAmB,MAAMC,0CAAgB,UAC7C,aAAa,WACb,KAAK,WACL,aAAa,MACb,KAAK,MACL,aAAa,UACb,KAAK,UACL,EAAE,SAAS,KAAK,QAAS,EAC1B;EACD,MAAM,aAAa,MAAM,kBAAkB,qBACzC,KAAK,QAAQ,EACb,OACA,aAAa,OACb,QACA,QACA,QACA,aAAa,QACd;AACD,MAAI;GACF,MAAM,UAAU,MAAM,KAAK,sBAAsB,OAAO,WAAW;GACnE,MAAM,YAAY,mBAAmB,QAAQ;AAC7C,UAAO;EACR,SAAQ,OAAO;GACd,MAAM,YAAY,qBAAqB,MAAM;AAC7C,SAAM;EACP;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["fields?: BaseRetrieverInput","_query: string","_callbacks?: CallbackManagerForRetrieverRun","input: string","options?: RunnableConfig"],"sources":["../../src/retrievers/index.ts"],"sourcesContent":["import {\n CallbackManager,\n CallbackManagerForRetrieverRun,\n Callbacks,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport type { DocumentInterface } from \"../documents/document.js\";\nimport { Runnable, type RunnableInterface } from \"../runnables/base.js\";\nimport { RunnableConfig, ensureConfig } from \"../runnables/config.js\";\n\n/**\n * Input configuration options for initializing a retriever that extends\n * the `BaseRetriever` class. This interface provides base properties\n * common to all retrievers, allowing customization of callback functions,\n * tagging, metadata, and logging verbosity.\n *\n * Fields:\n * - `callbacks` (optional): An array of callback functions that handle various\n * events during retrieval, such as logging, error handling, or progress updates.\n *\n * - `tags` (optional): An array of strings used to add contextual tags to\n * retrieval operations, allowing for easier categorization and tracking.\n *\n * - `metadata` (optional): A record of key-value pairs to store additional\n * contextual information for retrieval operations, which can be useful\n * for logging or auditing purposes.\n *\n * - `verbose` (optional): A boolean flag that, if set to `true`, enables\n * detailed logging and output during the retrieval process. Defaults to `false`.\n */\nexport interface BaseRetrieverInput {\n callbacks?: Callbacks;\n tags?: string[];\n metadata?: Record<string, unknown>;\n verbose?: boolean;\n}\n\n/**\n * Interface for a base retriever that defines core functionality for\n * retrieving relevant documents from a source based on a query.\n *\n * The `BaseRetrieverInterface` standardizes the `getRelevantDocuments` method,\n * enabling retrieval of documents that match the query criteria.\n *\n * @template Metadata - The type of metadata associated with each document,\n * defaulting to `Record<string, any>`.\n */\nexport interface BaseRetrieverInterface<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Metadata extends Record<string, any> = Record<string, any
|
|
1
|
+
{"version":3,"file":"index.js","names":["fields?: BaseRetrieverInput","_query: string","_callbacks?: CallbackManagerForRetrieverRun","input: string","options?: RunnableConfig"],"sources":["../../src/retrievers/index.ts"],"sourcesContent":["import {\n CallbackManager,\n CallbackManagerForRetrieverRun,\n Callbacks,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport type { DocumentInterface } from \"../documents/document.js\";\nimport { Runnable, type RunnableInterface } from \"../runnables/base.js\";\nimport { RunnableConfig, ensureConfig } from \"../runnables/config.js\";\n\n/**\n * Input configuration options for initializing a retriever that extends\n * the `BaseRetriever` class. This interface provides base properties\n * common to all retrievers, allowing customization of callback functions,\n * tagging, metadata, and logging verbosity.\n *\n * Fields:\n * - `callbacks` (optional): An array of callback functions that handle various\n * events during retrieval, such as logging, error handling, or progress updates.\n *\n * - `tags` (optional): An array of strings used to add contextual tags to\n * retrieval operations, allowing for easier categorization and tracking.\n *\n * - `metadata` (optional): A record of key-value pairs to store additional\n * contextual information for retrieval operations, which can be useful\n * for logging or auditing purposes.\n *\n * - `verbose` (optional): A boolean flag that, if set to `true`, enables\n * detailed logging and output during the retrieval process. Defaults to `false`.\n */\nexport interface BaseRetrieverInput {\n callbacks?: Callbacks;\n tags?: string[];\n metadata?: Record<string, unknown>;\n verbose?: boolean;\n}\n\n/**\n * Interface for a base retriever that defines core functionality for\n * retrieving relevant documents from a source based on a query.\n *\n * The `BaseRetrieverInterface` standardizes the `getRelevantDocuments` method,\n * enabling retrieval of documents that match the query criteria.\n *\n * @template Metadata - The type of metadata associated with each document,\n * defaulting to `Record<string, any>`.\n */\nexport interface BaseRetrieverInterface<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Metadata extends Record<string, any> = Record<string, any>,\n> extends RunnableInterface<string, DocumentInterface<Metadata>[]> {}\n\n/**\n * Abstract base class for a document retrieval system, designed to\n * process string queries and return the most relevant documents from a source.\n *\n * `BaseRetriever` provides common properties and methods for derived retrievers,\n * such as callbacks, tagging, and verbose logging. Custom retrieval systems\n * should extend this class and implement `_getRelevantDocuments` to define\n * the specific retrieval logic.\n *\n * @template Metadata - The type of metadata associated with each document,\n * defaulting to `Record<string, any>`.\n */\nexport abstract class BaseRetriever<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Metadata extends Record<string, any> = Record<string, any>,\n >\n extends Runnable<string, DocumentInterface<Metadata>[]>\n implements BaseRetrieverInterface\n{\n /**\n * Optional callbacks to handle various events in the retrieval process.\n */\n callbacks?: Callbacks;\n\n /**\n * Tags to label or categorize the retrieval operation.\n */\n tags?: string[];\n\n /**\n * Metadata to provide additional context or information about the retrieval\n * operation.\n */\n metadata?: Record<string, unknown>;\n\n /**\n * If set to `true`, enables verbose logging for the retrieval process.\n */\n verbose?: boolean;\n\n /**\n * Constructs a new `BaseRetriever` instance with optional configuration fields.\n *\n * @param fields - Optional input configuration that can include `callbacks`,\n * `tags`, `metadata`, and `verbose` settings for custom retriever behavior.\n */\n constructor(fields?: BaseRetrieverInput) {\n super(fields);\n this.callbacks = fields?.callbacks;\n this.tags = fields?.tags ?? [];\n this.metadata = fields?.metadata ?? {};\n this.verbose = fields?.verbose ?? false;\n }\n\n /**\n * TODO: This should be an abstract method, but we'd like to avoid breaking\n * changes to people currently using subclassed custom retrievers.\n * Change it on next major release.\n */\n /**\n * Placeholder method for retrieving relevant documents based on a query.\n *\n * This method is intended to be implemented by subclasses and will be\n * converted to an abstract method in the next major release. Currently, it\n * throws an error if not implemented, ensuring that custom retrievers define\n * the specific retrieval logic.\n *\n * @param _query - The query string used to search for relevant documents.\n * @param _callbacks - (optional) Callback manager for managing callbacks\n * during retrieval.\n * @returns A promise resolving to an array of `DocumentInterface` instances relevant to the query.\n * @throws {Error} Throws an error indicating the method is not implemented.\n */\n _getRelevantDocuments(\n _query: string,\n _callbacks?: CallbackManagerForRetrieverRun\n ): Promise<DocumentInterface<Metadata>[]> {\n throw new Error(\"Not implemented!\");\n }\n\n /**\n * Executes a retrieval operation.\n *\n * @param input - The query string used to search for relevant documents.\n * @param options - (optional) Configuration options for the retrieval run,\n * which may include callbacks, tags, and metadata.\n * @returns A promise that resolves to an array of `DocumentInterface` instances\n * representing the most relevant documents to the query.\n */\n async invoke(\n input: string,\n options?: RunnableConfig\n ): Promise<DocumentInterface<Metadata>[]> {\n const parsedConfig = ensureConfig(parseCallbackConfigArg(options));\n const callbackManager_ = await CallbackManager.configure(\n parsedConfig.callbacks,\n this.callbacks,\n parsedConfig.tags,\n this.tags,\n parsedConfig.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const runManager = await callbackManager_?.handleRetrieverStart(\n this.toJSON(),\n input,\n parsedConfig.runId,\n undefined,\n undefined,\n undefined,\n parsedConfig.runName\n );\n try {\n const results = await this._getRelevantDocuments(input, runManager);\n await runManager?.handleRetrieverEnd(results);\n return results;\n } catch (error) {\n await runManager?.handleRetrieverError(error);\n throw error;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgEA,IAAsB,gBAAtB,cAIU,SAEV;;;;CAIE;;;;CAKA;;;;;CAMA;;;;CAKA;;;;;;;CAQA,YAAYA,QAA6B;EACvC,MAAM,OAAO;EACb,KAAK,YAAY,QAAQ;EACzB,KAAK,OAAO,QAAQ,QAAQ,CAAE;EAC9B,KAAK,WAAW,QAAQ,YAAY,CAAE;EACtC,KAAK,UAAU,QAAQ,WAAW;CACnC;;;;;;;;;;;;;;;;;;;;CAqBD,sBACEC,QACAC,YACwC;AACxC,QAAM,IAAI,MAAM;CACjB;;;;;;;;;;CAWD,MAAM,OACJC,OACAC,SACwC;EACxC,MAAM,eAAe,aAAa,uBAAuB,QAAQ,CAAC;EAClE,MAAM,mBAAmB,MAAM,gBAAgB,UAC7C,aAAa,WACb,KAAK,WACL,aAAa,MACb,KAAK,MACL,aAAa,UACb,KAAK,UACL,EAAE,SAAS,KAAK,QAAS,EAC1B;EACD,MAAM,aAAa,MAAM,kBAAkB,qBACzC,KAAK,QAAQ,EACb,OACA,aAAa,OACb,QACA,QACA,QACA,aAAa,QACd;AACD,MAAI;GACF,MAAM,UAAU,MAAM,KAAK,sBAAsB,OAAO,WAAW;GACnE,MAAM,YAAY,mBAAmB,QAAQ;AAC7C,UAAO;EACR,SAAQ,OAAO;GACd,MAAM,YAAY,qBAAqB,MAAM;AAC7C,SAAM;EACP;CACF;AACF"}
|