@langchain/core 1.1.19 → 1.1.20
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/caches/index.d.cts.map +1 -1
- package/dist/callbacks/base.cjs.map +1 -1
- package/dist/callbacks/base.d.cts.map +1 -1
- package/dist/callbacks/base.js.map +1 -1
- package/dist/documents/document.cjs.map +1 -1
- package/dist/documents/document.js.map +1 -1
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.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.d.cts.map +1 -1
- package/dist/load/serializable.cjs.map +1 -1
- package/dist/load/serializable.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/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/message.cjs.map +1 -1
- package/dist/messages/message.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/xml.cjs.map +1 -1
- package/dist/output_parsers/xml.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/few_shot.cjs.map +1 -1
- package/dist/prompts/few_shot.js.map +1 -1
- package/dist/prompts/prompt.cjs.map +1 -1
- package/dist/prompts/prompt.js.map +1 -1
- package/dist/prompts/structured.cjs.map +1 -1
- package/dist/prompts/structured.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/history.cjs.map +1 -1
- package/dist/runnables/history.js.map +1 -1
- package/dist/stores.d.ts.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/tracers/event_stream.cjs.map +1 -1
- package/dist/tracers/event_stream.js.map +1 -1
- package/dist/tracers/log_stream.cjs.map +1 -1
- package/dist/tracers/log_stream.js.map +1 -1
- package/dist/utils/fast-json-patch/src/core.cjs +3 -10
- package/dist/utils/fast-json-patch/src/core.cjs.map +1 -1
- package/dist/utils/fast-json-patch/src/core.js +3 -10
- package/dist/utils/fast-json-patch/src/core.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/vectorstores.cjs.map +1 -1
- package/dist/vectorstores.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"few_shot.cjs","names":["BaseStringPromptTemplate","input: FewShotPromptTemplateInput","totalInputVariables: string[]","checkValidTemplate","inputVariables: InputValues","values: PartialValues<NewPartialVariableName>","values: InputValues","renderTemplate","data: SerializedFewShotTemplate","PromptTemplate","examples: Example[]","BaseChatPromptTemplate","fields: FewShotChatMessagePromptTemplateInput","values: TypedPromptInputValues<RunInput>","result: Record<string, any>","messages: BaseMessage[]","values: PartialValues<PartialVariableName>"],"sources":["../../src/prompts/few_shot.ts"],"sourcesContent":["import { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n Example,\n} from \"./base.js\";\nimport type { BaseExampleSelector } from \"../example_selectors/base.js\";\nimport {\n type TemplateFormat,\n checkValidTemplate,\n renderTemplate,\n} from \"./template.js\";\nimport { PromptTemplate } from \"./prompt.js\";\nimport type { SerializedFewShotTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport type { BaseMessage } from \"../messages/index.js\";\nimport {\n BaseChatPromptTemplate,\n type BaseMessagePromptTemplate,\n} from \"./chat.js\";\n\nexport interface FewShotPromptTemplateInput\n extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector;\n\n /**\n * An {@link PromptTemplate} used to format a single example.\n */\n examplePrompt: PromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n */\n exampleSeparator?: string;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Prompt template that contains few-shot examples.\n * @augments BasePromptTemplate\n * @augments FewShotPromptTemplateInput\n * @example\n * ```typescript\n * const examplePrompt = PromptTemplate.fromTemplate(\n * \"Input: {input}\\nOutput: {output}\",\n * );\n *\n * const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples(\n * [\n * { input: \"happy\", output: \"sad\" },\n * { input: \"tall\", output: \"short\" },\n * { input: \"energetic\", output: \"lethargic\" },\n * { input: \"sunny\", output: \"gloomy\" },\n * { input: \"windy\", output: \"calm\" },\n * ],\n * new OpenAIEmbeddings(),\n * HNSWLib,\n * { k: 1 },\n * );\n *\n * const dynamicPrompt = new FewShotPromptTemplate({\n * exampleSelector,\n * examplePrompt,\n * prefix: \"Give the antonym of every input\",\n * suffix: \"Input: {adjective}\\nOutput:\",\n * inputVariables: [\"adjective\"],\n * });\n *\n * // Format the dynamic prompt with the input 'rainy'\n * console.log(await dynamicPrompt.format({ adjective: \"rainy\" }));\n *\n * ```\n */\nexport class FewShotPromptTemplate\n extends BaseStringPromptTemplate\n implements FewShotPromptTemplateInput\n{\n lc_serializable = false;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: PromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n constructor(input: FewShotPromptTemplateInput) {\n super(input);\n Object.assign(this, input);\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"few_shot\" {\n return \"few_shot\";\n }\n\n static lc_name() {\n return \"FewShotPromptTemplate\";\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n );\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n };\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotPromptTemplate(promptDict);\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: InputValues): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n\n const exampleStrings = await Promise.all(\n examples.map((example) => this.examplePrompt.format(example))\n );\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n serialize(): SerializedFewShotTemplate {\n if (this.exampleSelector || !this.examples) {\n throw new Error(\n \"Serializing an example selector is not currently supported\"\n );\n }\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Serializing an output parser is not currently supported\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n example_prompt: this.examplePrompt.serialize(),\n example_separator: this.exampleSeparator,\n suffix: this.suffix,\n prefix: this.prefix,\n template_format: this.templateFormat,\n examples: this.examples,\n };\n }\n\n static async deserialize(\n data: SerializedFewShotTemplate\n ): Promise<FewShotPromptTemplate> {\n const { example_prompt } = data;\n if (!example_prompt) {\n throw new Error(\"Missing example prompt\");\n }\n const examplePrompt = await PromptTemplate.deserialize(example_prompt);\n\n let examples: Example[];\n\n if (Array.isArray(data.examples)) {\n examples = data.examples;\n } else {\n throw new Error(\n \"Invalid examples format. Only list or string are supported.\"\n );\n }\n\n return new FewShotPromptTemplate({\n inputVariables: data.input_variables,\n examplePrompt,\n examples,\n exampleSeparator: data.example_separator,\n prefix: data.prefix,\n suffix: data.suffix,\n templateFormat: data.template_format,\n });\n }\n}\n\nexport interface FewShotChatMessagePromptTemplateInput\n extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseMessagePromptTemplate} | {@link BaseChatPromptTemplate} used to format a single example.\n */\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n *\n * @defaultValue `\"\\n\\n\"`\n */\n exampleSeparator?: string;\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector | undefined;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n *\n * @defaultValue `\"\"`\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n *\n * @defaultValue `f-string`\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Chat prompt template that contains few-shot examples.\n * @augments BasePromptTemplateInput\n * @augments FewShotChatMessagePromptTemplateInput\n */\nexport class FewShotChatMessagePromptTemplate<\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 BaseChatPromptTemplate\n implements FewShotChatMessagePromptTemplateInput\n{\n lc_serializable = true;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n _getPromptType(): \"few_shot_chat\" {\n return \"few_shot_chat\";\n }\n\n static lc_name() {\n return \"FewShotChatMessagePromptTemplate\";\n }\n\n constructor(fields: FewShotChatMessagePromptTemplateInput) {\n super(fields);\n\n this.examples = fields.examples;\n this.examplePrompt = fields.examplePrompt;\n this.exampleSeparator = fields.exampleSeparator ?? \"\\n\\n\";\n this.exampleSelector = fields.exampleSelector;\n this.prefix = fields.prefix ?? \"\";\n this.suffix = fields.suffix ?? \"\";\n this.templateFormat = fields.templateFormat ?? \"f-string\";\n this.validateTemplate = fields.validateTemplate ?? true;\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n /**\n * Formats the list of values and returns a list of formatted messages.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n const allValues = await this.mergePartialAndUserVariables(values);\n let examples = await this.getExamples(allValues);\n\n examples = examples.map((example) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n this.examplePrompt.inputVariables.forEach((inputVariable) => {\n result[inputVariable] = example[inputVariable];\n });\n return result;\n });\n\n const messages: BaseMessage[] = [];\n for (const example of examples) {\n const exampleMessages = await this.examplePrompt.formatMessages(example);\n messages.push(...exampleMessages);\n }\n return messages;\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n const exampleMessages = await Promise.all(\n examples.map((example) => this.examplePrompt.formatMessages(example))\n );\n const exampleStrings = exampleMessages\n .flat()\n .map((message) => message.content);\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n /**\n * Partially formats the prompt with the given values.\n * @param values The values to partially format the prompt with.\n * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted.\n */\n async partial(\n values: PartialValues<PartialVariableName>\n ): Promise<FewShotChatMessagePromptTemplate<RunInput, PartialVariableName>> {\n const newInputVariables = this.inputVariables.filter(\n (variable) => !(variable in values)\n ) as Exclude<Extract<keyof RunInput, string>, PartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | PartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotChatMessagePromptTemplate<\n InputValues<Exclude<Extract<keyof RunInput, string>, PartialVariableName>>\n >(promptDict);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,IAAa,wBAAb,MAAa,8BACHA,wCAEV;CACE,kBAAkB;CAElB;CAEA;CAEA;CAEA,SAAS;CAET,mBAAmB;CAEnB,SAAS;CAET,iBAAiC;CAEjC,mBAAmB;CAEnB,YAAYC,OAAmC;EAC7C,MAAM,MAAM;EACZ,OAAO,OAAO,MAAM,MAAM;AAE1B,MAAI,KAAK,aAAa,UAAa,KAAK,oBAAoB,OAC1D,OAAM,IAAI,MACR;AAIJ,MAAI,KAAK,aAAa,UAAa,KAAK,oBAAoB,OAC1D,OAAM,IAAI,MACR;AAIJ,MAAI,KAAK,kBAAkB;GACzB,IAAIC,sBAAgC,KAAK;AACzC,OAAI,KAAK,kBACP,sBAAsB,oBAAoB,OACxC,OAAO,KAAK,KAAK,iB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AAM,aAAa;GACjB,GAAG;GACH,gBAAgB;GAChB,kBAAkB;EACnB;AACD,SAAO,IAAI,iCAET;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"few_shot.cjs","names":["BaseStringPromptTemplate","input: FewShotPromptTemplateInput","totalInputVariables: string[]","checkValidTemplate","inputVariables: InputValues","values: PartialValues<NewPartialVariableName>","values: InputValues","renderTemplate","data: SerializedFewShotTemplate","PromptTemplate","examples: Example[]","BaseChatPromptTemplate","fields: FewShotChatMessagePromptTemplateInput","values: TypedPromptInputValues<RunInput>","result: Record<string, any>","messages: BaseMessage[]","values: PartialValues<PartialVariableName>"],"sources":["../../src/prompts/few_shot.ts"],"sourcesContent":["import { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n Example,\n} from \"./base.js\";\nimport type { BaseExampleSelector } from \"../example_selectors/base.js\";\nimport {\n type TemplateFormat,\n checkValidTemplate,\n renderTemplate,\n} from \"./template.js\";\nimport { PromptTemplate } from \"./prompt.js\";\nimport type { SerializedFewShotTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport type { BaseMessage } from \"../messages/index.js\";\nimport {\n BaseChatPromptTemplate,\n type BaseMessagePromptTemplate,\n} from \"./chat.js\";\n\nexport interface FewShotPromptTemplateInput extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector;\n\n /**\n * An {@link PromptTemplate} used to format a single example.\n */\n examplePrompt: PromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n */\n exampleSeparator?: string;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Prompt template that contains few-shot examples.\n * @augments BasePromptTemplate\n * @augments FewShotPromptTemplateInput\n * @example\n * ```typescript\n * const examplePrompt = PromptTemplate.fromTemplate(\n * \"Input: {input}\\nOutput: {output}\",\n * );\n *\n * const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples(\n * [\n * { input: \"happy\", output: \"sad\" },\n * { input: \"tall\", output: \"short\" },\n * { input: \"energetic\", output: \"lethargic\" },\n * { input: \"sunny\", output: \"gloomy\" },\n * { input: \"windy\", output: \"calm\" },\n * ],\n * new OpenAIEmbeddings(),\n * HNSWLib,\n * { k: 1 },\n * );\n *\n * const dynamicPrompt = new FewShotPromptTemplate({\n * exampleSelector,\n * examplePrompt,\n * prefix: \"Give the antonym of every input\",\n * suffix: \"Input: {adjective}\\nOutput:\",\n * inputVariables: [\"adjective\"],\n * });\n *\n * // Format the dynamic prompt with the input 'rainy'\n * console.log(await dynamicPrompt.format({ adjective: \"rainy\" }));\n *\n * ```\n */\nexport class FewShotPromptTemplate\n extends BaseStringPromptTemplate\n implements FewShotPromptTemplateInput\n{\n lc_serializable = false;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: PromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n constructor(input: FewShotPromptTemplateInput) {\n super(input);\n Object.assign(this, input);\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"few_shot\" {\n return \"few_shot\";\n }\n\n static lc_name() {\n return \"FewShotPromptTemplate\";\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n );\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n };\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotPromptTemplate(promptDict);\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: InputValues): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n\n const exampleStrings = await Promise.all(\n examples.map((example) => this.examplePrompt.format(example))\n );\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n serialize(): SerializedFewShotTemplate {\n if (this.exampleSelector || !this.examples) {\n throw new Error(\n \"Serializing an example selector is not currently supported\"\n );\n }\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Serializing an output parser is not currently supported\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n example_prompt: this.examplePrompt.serialize(),\n example_separator: this.exampleSeparator,\n suffix: this.suffix,\n prefix: this.prefix,\n template_format: this.templateFormat,\n examples: this.examples,\n };\n }\n\n static async deserialize(\n data: SerializedFewShotTemplate\n ): Promise<FewShotPromptTemplate> {\n const { example_prompt } = data;\n if (!example_prompt) {\n throw new Error(\"Missing example prompt\");\n }\n const examplePrompt = await PromptTemplate.deserialize(example_prompt);\n\n let examples: Example[];\n\n if (Array.isArray(data.examples)) {\n examples = data.examples;\n } else {\n throw new Error(\n \"Invalid examples format. Only list or string are supported.\"\n );\n }\n\n return new FewShotPromptTemplate({\n inputVariables: data.input_variables,\n examplePrompt,\n examples,\n exampleSeparator: data.example_separator,\n prefix: data.prefix,\n suffix: data.suffix,\n templateFormat: data.template_format,\n });\n }\n}\n\nexport interface FewShotChatMessagePromptTemplateInput extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseMessagePromptTemplate} | {@link BaseChatPromptTemplate} used to format a single example.\n */\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n *\n * @defaultValue `\"\\n\\n\"`\n */\n exampleSeparator?: string;\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector | undefined;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n *\n * @defaultValue `\"\"`\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n *\n * @defaultValue `f-string`\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Chat prompt template that contains few-shot examples.\n * @augments BasePromptTemplateInput\n * @augments FewShotChatMessagePromptTemplateInput\n */\nexport class FewShotChatMessagePromptTemplate<\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 BaseChatPromptTemplate\n implements FewShotChatMessagePromptTemplateInput\n{\n lc_serializable = true;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n _getPromptType(): \"few_shot_chat\" {\n return \"few_shot_chat\";\n }\n\n static lc_name() {\n return \"FewShotChatMessagePromptTemplate\";\n }\n\n constructor(fields: FewShotChatMessagePromptTemplateInput) {\n super(fields);\n\n this.examples = fields.examples;\n this.examplePrompt = fields.examplePrompt;\n this.exampleSeparator = fields.exampleSeparator ?? \"\\n\\n\";\n this.exampleSelector = fields.exampleSelector;\n this.prefix = fields.prefix ?? \"\";\n this.suffix = fields.suffix ?? \"\";\n this.templateFormat = fields.templateFormat ?? \"f-string\";\n this.validateTemplate = fields.validateTemplate ?? true;\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n /**\n * Formats the list of values and returns a list of formatted messages.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n const allValues = await this.mergePartialAndUserVariables(values);\n let examples = await this.getExamples(allValues);\n\n examples = examples.map((example) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n this.examplePrompt.inputVariables.forEach((inputVariable) => {\n result[inputVariable] = example[inputVariable];\n });\n return result;\n });\n\n const messages: BaseMessage[] = [];\n for (const example of examples) {\n const exampleMessages = await this.examplePrompt.formatMessages(example);\n messages.push(...exampleMessages);\n }\n return messages;\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n const exampleMessages = await Promise.all(\n examples.map((example) => this.examplePrompt.formatMessages(example))\n );\n const exampleStrings = exampleMessages\n .flat()\n .map((message) => message.content);\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n /**\n * Partially formats the prompt with the given values.\n * @param values The values to partially format the prompt with.\n * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted.\n */\n async partial(\n values: PartialValues<PartialVariableName>\n ): Promise<FewShotChatMessagePromptTemplate<RunInput, PartialVariableName>> {\n const newInputVariables = this.inputVariables.filter(\n (variable) => !(variable in values)\n ) as Exclude<Extract<keyof RunInput, string>, PartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | PartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotChatMessagePromptTemplate<\n InputValues<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OF,QAA2D;EACtE,MAAM,YAAY,MAAM,KAAK,6BAA6B,OAAO;EACjE,MAAM,WAAW,MAAM,KAAK,YAAY,UAAU;EAClD,MAAM,kBAAkB,MAAM,QAAQ,IACpC,SAAS,IAAI,CAAC,YAAY,KAAK,cAAc,eAAe,QAAQ,CAAC,CACtE;EACD,MAAM,iBAAiB,gBACpB,MAAM,CACN,IAAI,CAAC,YAAY,QAAQ,QAAQ;EACpC,MAAM,WAAW;GAAC,KAAK;GAAQ,GAAG;GAAgB,KAAK;EAAO,EAAC,KAC7D,KAAK,iBACN;AACD,SAAON,gCAAe,UAAU,KAAK,gBAAgB,UAAU;CAChE;;;;;;CAOD,MAAM,QACJS,QAC0E;EAC1E,MAAM,oBAAoB,KAAK,eAAe,OAC5C,CAAC,aAAa,EAAE,YAAY,QAC7B;EACD,MAAM,sBAAsB;GAC1B,GAAI,KAAK,oBAAoB,CAAE;GAC/B,GAAG;EACJ;EACD,MAAM,aAAa;GACjB,GAAG;GACH,gBAAgB;GAChB,kBAAkB;EACnB;AACD,SAAO,IAAI,iCAET;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"few_shot.js","names":["input: FewShotPromptTemplateInput","totalInputVariables: string[]","inputVariables: InputValues","values: PartialValues<NewPartialVariableName>","values: InputValues","data: SerializedFewShotTemplate","examples: Example[]","fields: FewShotChatMessagePromptTemplateInput","values: TypedPromptInputValues<RunInput>","result: Record<string, any>","messages: BaseMessage[]","values: PartialValues<PartialVariableName>"],"sources":["../../src/prompts/few_shot.ts"],"sourcesContent":["import { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n Example,\n} from \"./base.js\";\nimport type { BaseExampleSelector } from \"../example_selectors/base.js\";\nimport {\n type TemplateFormat,\n checkValidTemplate,\n renderTemplate,\n} from \"./template.js\";\nimport { PromptTemplate } from \"./prompt.js\";\nimport type { SerializedFewShotTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport type { BaseMessage } from \"../messages/index.js\";\nimport {\n BaseChatPromptTemplate,\n type BaseMessagePromptTemplate,\n} from \"./chat.js\";\n\nexport interface FewShotPromptTemplateInput\n extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector;\n\n /**\n * An {@link PromptTemplate} used to format a single example.\n */\n examplePrompt: PromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n */\n exampleSeparator?: string;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Prompt template that contains few-shot examples.\n * @augments BasePromptTemplate\n * @augments FewShotPromptTemplateInput\n * @example\n * ```typescript\n * const examplePrompt = PromptTemplate.fromTemplate(\n * \"Input: {input}\\nOutput: {output}\",\n * );\n *\n * const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples(\n * [\n * { input: \"happy\", output: \"sad\" },\n * { input: \"tall\", output: \"short\" },\n * { input: \"energetic\", output: \"lethargic\" },\n * { input: \"sunny\", output: \"gloomy\" },\n * { input: \"windy\", output: \"calm\" },\n * ],\n * new OpenAIEmbeddings(),\n * HNSWLib,\n * { k: 1 },\n * );\n *\n * const dynamicPrompt = new FewShotPromptTemplate({\n * exampleSelector,\n * examplePrompt,\n * prefix: \"Give the antonym of every input\",\n * suffix: \"Input: {adjective}\\nOutput:\",\n * inputVariables: [\"adjective\"],\n * });\n *\n * // Format the dynamic prompt with the input 'rainy'\n * console.log(await dynamicPrompt.format({ adjective: \"rainy\" }));\n *\n * ```\n */\nexport class FewShotPromptTemplate\n extends BaseStringPromptTemplate\n implements FewShotPromptTemplateInput\n{\n lc_serializable = false;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: PromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n constructor(input: FewShotPromptTemplateInput) {\n super(input);\n Object.assign(this, input);\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"few_shot\" {\n return \"few_shot\";\n }\n\n static lc_name() {\n return \"FewShotPromptTemplate\";\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n );\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n };\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotPromptTemplate(promptDict);\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: InputValues): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n\n const exampleStrings = await Promise.all(\n examples.map((example) => this.examplePrompt.format(example))\n );\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n serialize(): SerializedFewShotTemplate {\n if (this.exampleSelector || !this.examples) {\n throw new Error(\n \"Serializing an example selector is not currently supported\"\n );\n }\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Serializing an output parser is not currently supported\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n example_prompt: this.examplePrompt.serialize(),\n example_separator: this.exampleSeparator,\n suffix: this.suffix,\n prefix: this.prefix,\n template_format: this.templateFormat,\n examples: this.examples,\n };\n }\n\n static async deserialize(\n data: SerializedFewShotTemplate\n ): Promise<FewShotPromptTemplate> {\n const { example_prompt } = data;\n if (!example_prompt) {\n throw new Error(\"Missing example prompt\");\n }\n const examplePrompt = await PromptTemplate.deserialize(example_prompt);\n\n let examples: Example[];\n\n if (Array.isArray(data.examples)) {\n examples = data.examples;\n } else {\n throw new Error(\n \"Invalid examples format. Only list or string are supported.\"\n );\n }\n\n return new FewShotPromptTemplate({\n inputVariables: data.input_variables,\n examplePrompt,\n examples,\n exampleSeparator: data.example_separator,\n prefix: data.prefix,\n suffix: data.suffix,\n templateFormat: data.template_format,\n });\n }\n}\n\nexport interface FewShotChatMessagePromptTemplateInput\n extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseMessagePromptTemplate} | {@link BaseChatPromptTemplate} used to format a single example.\n */\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n *\n * @defaultValue `\"\\n\\n\"`\n */\n exampleSeparator?: string;\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector | undefined;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n *\n * @defaultValue `\"\"`\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n *\n * @defaultValue `f-string`\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Chat prompt template that contains few-shot examples.\n * @augments BasePromptTemplateInput\n * @augments FewShotChatMessagePromptTemplateInput\n */\nexport class FewShotChatMessagePromptTemplate<\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 BaseChatPromptTemplate\n implements FewShotChatMessagePromptTemplateInput\n{\n lc_serializable = true;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n _getPromptType(): \"few_shot_chat\" {\n return \"few_shot_chat\";\n }\n\n static lc_name() {\n return \"FewShotChatMessagePromptTemplate\";\n }\n\n constructor(fields: FewShotChatMessagePromptTemplateInput) {\n super(fields);\n\n this.examples = fields.examples;\n this.examplePrompt = fields.examplePrompt;\n this.exampleSeparator = fields.exampleSeparator ?? \"\\n\\n\";\n this.exampleSelector = fields.exampleSelector;\n this.prefix = fields.prefix ?? \"\";\n this.suffix = fields.suffix ?? \"\";\n this.templateFormat = fields.templateFormat ?? \"f-string\";\n this.validateTemplate = fields.validateTemplate ?? true;\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n /**\n * Formats the list of values and returns a list of formatted messages.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n const allValues = await this.mergePartialAndUserVariables(values);\n let examples = await this.getExamples(allValues);\n\n examples = examples.map((example) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n this.examplePrompt.inputVariables.forEach((inputVariable) => {\n result[inputVariable] = example[inputVariable];\n });\n return result;\n });\n\n const messages: BaseMessage[] = [];\n for (const example of examples) {\n const exampleMessages = await this.examplePrompt.formatMessages(example);\n messages.push(...exampleMessages);\n }\n return messages;\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n const exampleMessages = await Promise.all(\n examples.map((example) => this.examplePrompt.formatMessages(example))\n );\n const exampleStrings = exampleMessages\n .flat()\n .map((message) => message.content);\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n /**\n * Partially formats the prompt with the given values.\n * @param values The values to partially format the prompt with.\n * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted.\n */\n async partial(\n values: PartialValues<PartialVariableName>\n ): Promise<FewShotChatMessagePromptTemplate<RunInput, PartialVariableName>> {\n const newInputVariables = this.inputVariables.filter(\n (variable) => !(variable in values)\n ) as Exclude<Extract<keyof RunInput, string>, PartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | PartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotChatMessagePromptTemplate<\n InputValues<Exclude<Extract<keyof RunInput, string>, PartialVariableName>>\n >(promptDict);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,IAAa,wBAAb,MAAa,8BACH,yBAEV;CACE,kBAAkB;CAElB;CAEA;CAEA;CAEA,SAAS;CAET,mBAAmB;CAEnB,SAAS;CAET,iBAAiC;CAEjC,mBAAmB;CAEnB,YAAYA,OAAmC;EAC7C,MAAM,MAAM;EACZ,OAAO,OAAO,MAAM,MAAM;AAE1B,MAAI,KAAK,aAAa,UAAa,KAAK,oBAAoB,OAC1D,OAAM,IAAI,MACR;AAIJ,MAAI,KAAK,aAAa,UAAa,KAAK,oBAAoB,OAC1D,OAAM,IAAI,MACR;AAIJ,MAAI,KAAK,kBAAkB;GACzB,IAAIC,sBAAgC,KAAK;AACzC,OAAI,KAAK,kBACP,sBAAsB,oBAAoB,OACxC,OAAO,KAAK,KAAK,iBAAiB,CACnC;GAEH,mBACE,KAAK,SAAS,KAAK,QACnB,KAAK,gBACL,oBACD;EACF;CACF;CAED,iBAA6B;AAC3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{"version":3,"file":"few_shot.js","names":["input: FewShotPromptTemplateInput","totalInputVariables: string[]","inputVariables: InputValues","values: PartialValues<NewPartialVariableName>","values: InputValues","data: SerializedFewShotTemplate","examples: Example[]","fields: FewShotChatMessagePromptTemplateInput","values: TypedPromptInputValues<RunInput>","result: Record<string, any>","messages: BaseMessage[]","values: PartialValues<PartialVariableName>"],"sources":["../../src/prompts/few_shot.ts"],"sourcesContent":["import { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n Example,\n} from \"./base.js\";\nimport type { BaseExampleSelector } from \"../example_selectors/base.js\";\nimport {\n type TemplateFormat,\n checkValidTemplate,\n renderTemplate,\n} from \"./template.js\";\nimport { PromptTemplate } from \"./prompt.js\";\nimport type { SerializedFewShotTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport type { BaseMessage } from \"../messages/index.js\";\nimport {\n BaseChatPromptTemplate,\n type BaseMessagePromptTemplate,\n} from \"./chat.js\";\n\nexport interface FewShotPromptTemplateInput extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector;\n\n /**\n * An {@link PromptTemplate} used to format a single example.\n */\n examplePrompt: PromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n */\n exampleSeparator?: string;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Prompt template that contains few-shot examples.\n * @augments BasePromptTemplate\n * @augments FewShotPromptTemplateInput\n * @example\n * ```typescript\n * const examplePrompt = PromptTemplate.fromTemplate(\n * \"Input: {input}\\nOutput: {output}\",\n * );\n *\n * const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples(\n * [\n * { input: \"happy\", output: \"sad\" },\n * { input: \"tall\", output: \"short\" },\n * { input: \"energetic\", output: \"lethargic\" },\n * { input: \"sunny\", output: \"gloomy\" },\n * { input: \"windy\", output: \"calm\" },\n * ],\n * new OpenAIEmbeddings(),\n * HNSWLib,\n * { k: 1 },\n * );\n *\n * const dynamicPrompt = new FewShotPromptTemplate({\n * exampleSelector,\n * examplePrompt,\n * prefix: \"Give the antonym of every input\",\n * suffix: \"Input: {adjective}\\nOutput:\",\n * inputVariables: [\"adjective\"],\n * });\n *\n * // Format the dynamic prompt with the input 'rainy'\n * console.log(await dynamicPrompt.format({ adjective: \"rainy\" }));\n *\n * ```\n */\nexport class FewShotPromptTemplate\n extends BaseStringPromptTemplate\n implements FewShotPromptTemplateInput\n{\n lc_serializable = false;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: PromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n constructor(input: FewShotPromptTemplateInput) {\n super(input);\n Object.assign(this, input);\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"few_shot\" {\n return \"few_shot\";\n }\n\n static lc_name() {\n return \"FewShotPromptTemplate\";\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n );\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n };\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotPromptTemplate(promptDict);\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: InputValues): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n\n const exampleStrings = await Promise.all(\n examples.map((example) => this.examplePrompt.format(example))\n );\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n serialize(): SerializedFewShotTemplate {\n if (this.exampleSelector || !this.examples) {\n throw new Error(\n \"Serializing an example selector is not currently supported\"\n );\n }\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Serializing an output parser is not currently supported\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n example_prompt: this.examplePrompt.serialize(),\n example_separator: this.exampleSeparator,\n suffix: this.suffix,\n prefix: this.prefix,\n template_format: this.templateFormat,\n examples: this.examples,\n };\n }\n\n static async deserialize(\n data: SerializedFewShotTemplate\n ): Promise<FewShotPromptTemplate> {\n const { example_prompt } = data;\n if (!example_prompt) {\n throw new Error(\"Missing example prompt\");\n }\n const examplePrompt = await PromptTemplate.deserialize(example_prompt);\n\n let examples: Example[];\n\n if (Array.isArray(data.examples)) {\n examples = data.examples;\n } else {\n throw new Error(\n \"Invalid examples format. Only list or string are supported.\"\n );\n }\n\n return new FewShotPromptTemplate({\n inputVariables: data.input_variables,\n examplePrompt,\n examples,\n exampleSeparator: data.example_separator,\n prefix: data.prefix,\n suffix: data.suffix,\n templateFormat: data.template_format,\n });\n }\n}\n\nexport interface FewShotChatMessagePromptTemplateInput extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseMessagePromptTemplate} | {@link BaseChatPromptTemplate} used to format a single example.\n */\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n *\n * @defaultValue `\"\\n\\n\"`\n */\n exampleSeparator?: string;\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector | undefined;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n *\n * @defaultValue `\"\"`\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n *\n * @defaultValue `f-string`\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Chat prompt template that contains few-shot examples.\n * @augments BasePromptTemplateInput\n * @augments FewShotChatMessagePromptTemplateInput\n */\nexport class FewShotChatMessagePromptTemplate<\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 BaseChatPromptTemplate\n implements FewShotChatMessagePromptTemplateInput\n{\n lc_serializable = true;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n _getPromptType(): \"few_shot_chat\" {\n return \"few_shot_chat\";\n }\n\n static lc_name() {\n return \"FewShotChatMessagePromptTemplate\";\n }\n\n constructor(fields: FewShotChatMessagePromptTemplateInput) {\n super(fields);\n\n this.examples = fields.examples;\n this.examplePrompt = fields.examplePrompt;\n this.exampleSeparator = fields.exampleSeparator ?? \"\\n\\n\";\n this.exampleSelector = fields.exampleSelector;\n this.prefix = fields.prefix ?? \"\";\n this.suffix = fields.suffix ?? \"\";\n this.templateFormat = fields.templateFormat ?? \"f-string\";\n this.validateTemplate = fields.validateTemplate ?? true;\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n /**\n * Formats the list of values and returns a list of formatted messages.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n const allValues = await this.mergePartialAndUserVariables(values);\n let examples = await this.getExamples(allValues);\n\n examples = examples.map((example) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n this.examplePrompt.inputVariables.forEach((inputVariable) => {\n result[inputVariable] = example[inputVariable];\n });\n return result;\n });\n\n const messages: BaseMessage[] = [];\n for (const example of examples) {\n const exampleMessages = await this.examplePrompt.formatMessages(example);\n messages.push(...exampleMessages);\n }\n return messages;\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n const exampleMessages = await Promise.all(\n examples.map((example) => this.examplePrompt.formatMessages(example))\n );\n const exampleStrings = exampleMessages\n .flat()\n .map((message) => message.content);\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n /**\n * Partially formats the prompt with the given values.\n * @param values The values to partially format the prompt with.\n * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted.\n */\n async partial(\n values: PartialValues<PartialVariableName>\n ): Promise<FewShotChatMessagePromptTemplate<RunInput, PartialVariableName>> {\n const newInputVariables = this.inputVariables.filter(\n (variable) => !(variable in values)\n ) as Exclude<Extract<keyof RunInput, string>, PartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | PartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotChatMessagePromptTemplate<\n InputValues<Exclude<Extract<keyof RunInput, string>, PartialVariableName>>\n >(promptDict);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyGA,IAAa,wBAAb,MAAa,8BACH,yBAEV;CACE,kBAAkB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Ae,QAAQ,CAAC,CACtE;EACD,MAAM,iBAAiB,gBACpB,MAAM,CACN,IAAI,CAAC,YAAY,QAAQ,QAAQ;EACpC,MAAM,WAAW;GAAC,KAAK;GAAQ,GAAG;GAAgB,KAAK;EAAO,EAAC,KAC7D,KAAK,iBACN;AACD,SAAO,eAAe,UAAU,KAAK,gBAAgB,UAAU;CAChE;;;;;;CAOD,MAAM,QACJG,QAC0E;EAC1E,MAAM,oBAAoB,KAAK,eAAe,OAC5C,CAAC,aAAa,EAAE,YAAY,QAC7B;EACD,MAAM,sBAAsB;GAC1B,GAAI,KAAK,oBAAoB,CAAE;GAC/B,GAAG;EACJ;EACD,MAAM,aAAa;GACjB,GAAG;GACH,gBAAgB;GAChB,kBAAkB;EACnB;AACD,SAAO,IAAI,iCAET;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.cjs","names":["BaseStringPromptTemplate","input: PromptTemplateInput<RunInput, PartialVariableName>","totalInputVariables: string[]","checkValidTemplate","values: TypedPromptInputValues<RunInput>","renderTemplate","examples: string[]","suffix: string","inputVariables: string[]","template: T","options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >","parseTemplate","values: PartialValues<NewPartialVariableName>","data: SerializedPromptTemplate"],"sources":["../../src/prompts/prompt.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n checkValidTemplate,\n parseTemplate,\n renderTemplate,\n type TemplateFormat,\n} from \"./template.js\";\nimport type { SerializedPromptTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport { MessageContent, ContentBlock } from \"../messages/index.js\";\n\n/**\n * Inputs to create a {@link PromptTemplate}\n * @augments BasePromptTemplateInput\n */\nexport interface PromptTemplateInput<\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 Format extends TemplateFormat = TemplateFormat,\n> extends BasePromptTemplateInput<RunInput, PartialVariableName> {\n /**\n * The prompt template\n */\n template: MessageContent;\n\n /**\n * The format of the prompt template. Options are \"f-string\" and \"mustache\"\n */\n templateFormat?: Format;\n\n /**\n * Whether or not to try validating the template on initialization\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n}\n\ntype NonAlphanumeric =\n | \" \"\n | \"\\t\"\n | \"\\n\"\n | \"\\r\"\n | '\"'\n | \"'\"\n | \"{\"\n | \"[\"\n | \"(\"\n | \"`\"\n | \":\"\n | \";\";\n\n/**\n * Recursive type to extract template parameters from a string.\n * @template T - The input string.\n * @template Result - The resulting array of extracted template parameters.\n */\ntype ExtractTemplateParamsRecursive<\n T extends string,\n Result extends string[] = [],\n> = T extends `${string}{${infer Param}}${infer Rest}`\n ? Param extends `${NonAlphanumeric}${string}`\n ? ExtractTemplateParamsRecursive<Rest, Result> // for non-template variables that look like template variables e.g. see https://github.com/langchain-ai/langchainjs/blob/main/langchain/src/chains/query_constructor/prompt.ts\n : ExtractTemplateParamsRecursive<Rest, [...Result, Param]>\n : Result;\n\nexport type ParamsFromFString<T extends string> = {\n [Key in\n | ExtractTemplateParamsRecursive<T>[number]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (string & Record<never, never>)]: any;\n};\n\nexport type ExtractedFStringParams<\n T extends string,\n RunInput extends InputValues = Symbol,\n> = RunInput extends Symbol ? ParamsFromFString<T> : RunInput;\n\n/**\n * Schema to represent a basic prompt for an LLM.\n * @augments BasePromptTemplate\n * @augments PromptTemplateInput\n *\n * @example\n * ```ts\n * import { PromptTemplate } from \"langchain/prompts\";\n *\n * const prompt = new PromptTemplate({\n * inputVariables: [\"foo\"],\n * template: \"Say {foo}\",\n * });\n * ```\n */\nexport class PromptTemplate<\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 BaseStringPromptTemplate<RunInput, PartialVariableName>\n implements PromptTemplateInput<RunInput, PartialVariableName>\n{\n static lc_name() {\n return \"PromptTemplate\";\n }\n\n template: MessageContent;\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n\n constructor(input: PromptTemplateInput<RunInput, PartialVariableName>) {\n super(input);\n // If input is mustache and validateTemplate is not defined, set it to false\n if (\n input.templateFormat === \"mustache\" &&\n input.validateTemplate === undefined\n ) {\n this.validateTemplate = false;\n }\n Object.assign(this, input);\n\n if (this.validateTemplate) {\n if (this.templateFormat === \"mustache\") {\n throw new Error(\"Mustache templates cannot be validated.\");\n }\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.template,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"prompt\" {\n return \"prompt\";\n }\n\n /**\n * Formats the prompt template with the provided values.\n * @param values The values to be used to format the prompt template.\n * @returns A promise that resolves to a string which is the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n return renderTemplate(\n this.template as string,\n this.templateFormat,\n allValues\n );\n }\n\n /**\n * Take examples in list format with prefix and suffix to create a prompt.\n *\n * Intended to be used a a way to dynamically create a prompt from examples.\n *\n * @param examples - List of examples to use in the prompt.\n * @param suffix - String to go after the list of examples. Should generally set up the user's input.\n * @param inputVariables - A list of variable names the final prompt template will expect\n * @param exampleSeparator - The separator to use in between examples\n * @param prefix - String that should go before any examples. Generally includes examples.\n *\n * @returns The final prompt template generated.\n */\n static fromExamples(\n examples: string[],\n suffix: string,\n inputVariables: string[],\n exampleSeparator = \"\\n\\n\",\n prefix = \"\"\n ) {\n const template = [prefix, ...examples, suffix].join(exampleSeparator);\n return new PromptTemplate({\n inputVariables,\n template,\n });\n }\n\n /**\n * Load prompt template from a template f-string\n */\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"f-string\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"mustache\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<InputValues>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput> | InputValues> {\n const { templateFormat = \"f-string\", ...rest } = options ?? {};\n const names = new Set<string>();\n parseTemplate(template, templateFormat).forEach((node) => {\n if (node.type === \"variable\") {\n names.add(node.name);\n }\n });\n\n return new PromptTemplate({\n // Rely on extracted types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputVariables: [...names] as any[],\n templateFormat,\n template,\n ...rest,\n });\n }\n\n /**\n * Partially applies values to the prompt template.\n * @param values The values to be partially applied to the prompt template.\n * @returns A new instance of PromptTemplate with the partially applied values.\n */\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n ) as Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | NewPartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new PromptTemplate<\n InputValues<\n Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>\n >\n >(promptDict);\n }\n\n serialize(): SerializedPromptTemplate {\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Cannot serialize a prompt template with an output parser\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n template: this.template,\n template_format: this.templateFormat,\n };\n }\n\n static async deserialize(\n data: SerializedPromptTemplate\n ): Promise<PromptTemplate> {\n if (!data.template) {\n throw new Error(\"Prompt template must have a template\");\n }\n const res = new PromptTemplate({\n inputVariables: data.input_variables,\n template: data.template,\n templateFormat: data.template_format,\n });\n return res;\n }\n\n // TODO(from file)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6GA,IAAa,iBAAb,MAAa,uBAMHA,wCAEV;CACE,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA,iBAAiC;CAEjC,mBAAmB;;;;;;CAOnB;CAEA,YAAYC,OAA2D;EACrE,MAAM,MAAM;AAEZ,MACE,MAAM,mBAAmB,cACzB,MAAM,qBAAqB,QAE3B,KAAK,mBAAmB;EAE1B,OAAO,OAAO,MAAM,MAAM;AAE1B,MAAI,KAAK,kBAAkB;AACzB,OAAI,KAAK,mBAAmB,WAC1B,OAAM,IAAI,MAAM;GAElB,IAAIC,sBAAgC,KAAK;AACzC,OAAI,KAAK,kBACP,sBAAsB,oBAAoB,OACxC,OAAO,KAAK,KAAK,iBAAiB,CACnC;GAEHC,oCACE,KAAK,UACL,KAAK,gBACL,oBACD;EACF;CACF;CAED,iB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AAU,KAAK;GACf,gBAAgB,KAAK;EACtB;AACD,SAAO;CACR;AAGF"}
|
|
1
|
+
{"version":3,"file":"prompt.cjs","names":["BaseStringPromptTemplate","input: PromptTemplateInput<RunInput, PartialVariableName>","totalInputVariables: string[]","checkValidTemplate","values: TypedPromptInputValues<RunInput>","renderTemplate","examples: string[]","suffix: string","inputVariables: string[]","template: T","options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >","parseTemplate","values: PartialValues<NewPartialVariableName>","data: SerializedPromptTemplate"],"sources":["../../src/prompts/prompt.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n checkValidTemplate,\n parseTemplate,\n renderTemplate,\n type TemplateFormat,\n} from \"./template.js\";\nimport type { SerializedPromptTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport { MessageContent, ContentBlock } from \"../messages/index.js\";\n\n/**\n * Inputs to create a {@link PromptTemplate}\n * @augments BasePromptTemplateInput\n */\nexport interface PromptTemplateInput<\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 Format extends TemplateFormat = TemplateFormat,\n> extends BasePromptTemplateInput<RunInput, PartialVariableName> {\n /**\n * The prompt template\n */\n template: MessageContent;\n\n /**\n * The format of the prompt template. Options are \"f-string\" and \"mustache\"\n */\n templateFormat?: Format;\n\n /**\n * Whether or not to try validating the template on initialization\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n}\n\ntype NonAlphanumeric =\n | \" \"\n | \"\\t\"\n | \"\\n\"\n | \"\\r\"\n | '\"'\n | \"'\"\n | \"{\"\n | \"[\"\n | \"(\"\n | \"`\"\n | \":\"\n | \";\";\n\n/**\n * Recursive type to extract template parameters from a string.\n * @template T - The input string.\n * @template Result - The resulting array of extracted template parameters.\n */\ntype ExtractTemplateParamsRecursive<\n T extends string,\n Result extends string[] = [],\n> = T extends `${string}{${infer Param}}${infer Rest}`\n ? Param extends `${NonAlphanumeric}${string}`\n ? ExtractTemplateParamsRecursive<Rest, Result> // for non-template variables that look like template variables e.g. see https://github.com/langchain-ai/langchainjs/blob/main/langchain/src/chains/query_constructor/prompt.ts\n : ExtractTemplateParamsRecursive<Rest, [...Result, Param]>\n : Result;\n\nexport type ParamsFromFString<T extends string> = {\n [Key in\n | ExtractTemplateParamsRecursive<T>[number]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (string & Record<never, never>)]: any;\n};\n\nexport type ExtractedFStringParams<\n T extends string,\n RunInput extends InputValues = Symbol,\n> = RunInput extends Symbol ? ParamsFromFString<T> : RunInput;\n\n/**\n * Schema to represent a basic prompt for an LLM.\n * @augments BasePromptTemplate\n * @augments PromptTemplateInput\n *\n * @example\n * ```ts\n * import { PromptTemplate } from \"langchain/prompts\";\n *\n * const prompt = new PromptTemplate({\n * inputVariables: [\"foo\"],\n * template: \"Say {foo}\",\n * });\n * ```\n */\nexport class PromptTemplate<\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 BaseStringPromptTemplate<RunInput, PartialVariableName>\n implements PromptTemplateInput<RunInput, PartialVariableName>\n{\n static lc_name() {\n return \"PromptTemplate\";\n }\n\n template: MessageContent;\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n\n constructor(input: PromptTemplateInput<RunInput, PartialVariableName>) {\n super(input);\n // If input is mustache and validateTemplate is not defined, set it to false\n if (\n input.templateFormat === \"mustache\" &&\n input.validateTemplate === undefined\n ) {\n this.validateTemplate = false;\n }\n Object.assign(this, input);\n\n if (this.validateTemplate) {\n if (this.templateFormat === \"mustache\") {\n throw new Error(\"Mustache templates cannot be validated.\");\n }\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.template,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"prompt\" {\n return \"prompt\";\n }\n\n /**\n * Formats the prompt template with the provided values.\n * @param values The values to be used to format the prompt template.\n * @returns A promise that resolves to a string which is the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n return renderTemplate(\n this.template as string,\n this.templateFormat,\n allValues\n );\n }\n\n /**\n * Take examples in list format with prefix and suffix to create a prompt.\n *\n * Intended to be used a a way to dynamically create a prompt from examples.\n *\n * @param examples - List of examples to use in the prompt.\n * @param suffix - String to go after the list of examples. Should generally set up the user's input.\n * @param inputVariables - A list of variable names the final prompt template will expect\n * @param exampleSeparator - The separator to use in between examples\n * @param prefix - String that should go before any examples. Generally includes examples.\n *\n * @returns The final prompt template generated.\n */\n static fromExamples(\n examples: string[],\n suffix: string,\n inputVariables: string[],\n exampleSeparator = \"\\n\\n\",\n prefix = \"\"\n ) {\n const template = [prefix, ...examples, suffix].join(exampleSeparator);\n return new PromptTemplate({\n inputVariables,\n template,\n });\n }\n\n /**\n * Load prompt template from a template f-string\n */\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"f-string\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"mustache\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<InputValues>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput> | InputValues> {\n const { templateFormat = \"f-string\", ...rest } = options ?? {};\n const names = new Set<string>();\n parseTemplate(template, templateFormat).forEach((node) => {\n if (node.type === \"variable\") {\n names.add(node.name);\n }\n });\n\n return new PromptTemplate({\n // Rely on extracted types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputVariables: [...names] as any[],\n templateFormat,\n template,\n ...rest,\n });\n }\n\n /**\n * Partially applies values to the prompt template.\n * @param values The values to be partially applied to the prompt template.\n * @returns A new instance of PromptTemplate with the partially applied values.\n */\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n ) as Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | NewPartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new PromptTemplate<\n InputValues<\n Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>\n >\n >(promptDict);\n }\n\n serialize(): SerializedPromptTemplate {\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Cannot serialize a prompt template with an output parser\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n template: this.template,\n template_format: this.templateFormat,\n };\n }\n\n static async deserialize(\n data: SerializedPromptTemplate\n ): Promise<PromptTemplate> {\n if (!data.template) {\n throw new Error(\"Prompt template must have a template\");\n }\n const res = new PromptTemplate({\n inputVariables: data.input_variables,\n template: data.template,\n templateFormat: data.template_format,\n });\n return res;\n }\n\n // TODO(from file)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6GA,IAAa,iBAAb,MAAa,uBAMHA,wCAEV;CACE,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA,iBAAiC;CAEjC,mBAAmB;;;;;;CAOnB;CAEA,YAAYC,OAA2D;EACrE,MAAM,MAAM;AAEZ,MACE,MAAM,mBAAmB,cACzB,MAAM,qBAAqB,QAE3B,KAAK,mBAAmB;EAE1B,OAAO,OAAO,MAAM,MAAM;AAE1B,MAAI,KAAK,kBAAkB;AACzB,OAAI,KAAK,mBAAmB,WAC1B,OAAM,IAAI,MAAM;GAElB,IAAIC,sBAAgC,KAAK;AACzC,OAAI,KAAK,kBACP,sBAAsB,oBAAoB,OACxC,OAAO,KAAK,KAAK,iBAAiB,CACnC;GAEHC,oCACE,KAAK,UACL,KAAK,gBACL,oBACD;EACF;CACF;CAED,iBAA2B;AACzB,SAAO;CACR;;;;;;CAOD,MAAM,OAAOC,QAA2D;EACtE,MAAM,YAAY,MAAM,KAAK,6BAA6B,OAAO;AACjE,SAAOC,gCACL,KAAK,UACL,KAAK,gBACL,UACD;CACF;;;;;;;;;;;;;;CAeD,OAAO,aACLC,UACAC,QACAC,gBACA,mBAAmB,QACnB,SAAS,IACT;EACA,MAAM,WAAW;GAAC;GAAQ,GAAG;GAAU;EAAO,EAAC,KAAK,iBAAiB;AACrE,SAAO,IAAI,eAAe;GACxB;GACA;EACD;CACF;CAsCD,OAAO,aAILC,UACAC,SAImE;EACnE,MAAM,EAAE,iBAAiB,WAAY,GAAG,MAAM,GAAG,WAAW,CAAE;EAC9D,MAAM,wBAAQ,IAAI;EAClBC,+BAAc,UAAU,eAAe,CAAC,QAAQ,CAAC,SAAS;AACxD,OAAI,KAAK,SAAS,YAChB,MAAM,IAAI,KAAK,KAAK;EAEvB,EAAC;AAEF,SAAO,IAAI,eAAe;GAGxB,gBAAgB,CAAC,GAAG,KAAM;GAC1B;GACA;GACA,GAAG;EACJ;CACF;;;;;;CAOD,MAAM,QACJC,QACA;EACA,MAAM,oBAAoB,KAAK,eAAe,OAC5C,CAAC,OAAO,EAAE,MAAM,QACjB;EACD,MAAM,sBAAsB;GAC1B,GAAI,KAAK,oBAAoB,CAAE;GAC/B,GAAG;EACJ;EACD,MAAM,aAAa;GACjB,GAAG;GACH,gBAAgB;GAChB,kBAAkB;EACnB;AACD,SAAO,IAAI,eAIT;CACH;CAED,YAAsC;AACpC,MAAI,KAAK,iBAAiB,OACxB,OAAM,IAAI,MACR;AAGJ,SAAO;GACL,OAAO,KAAK,gBAAgB;GAC5B,iBAAiB,KAAK;GACtB,UAAU,KAAK;GACf,iBAAiB,KAAK;EACvB;CACF;CAED,aAAa,YACXC,MACyB;AACzB,MAAI,CAAC,KAAK,SACR,OAAM,IAAI,MAAM;EAElB,MAAM,MAAM,IAAI,eAAe;GAC7B,gBAAgB,KAAK;GACrB,UAAU,KAAK;GACf,gBAAgB,KAAK;EACtB;AACD,SAAO;CACR;AAGF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.js","names":["input: PromptTemplateInput<RunInput, PartialVariableName>","totalInputVariables: string[]","values: TypedPromptInputValues<RunInput>","examples: string[]","suffix: string","inputVariables: string[]","template: T","options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >","values: PartialValues<NewPartialVariableName>","data: SerializedPromptTemplate"],"sources":["../../src/prompts/prompt.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n checkValidTemplate,\n parseTemplate,\n renderTemplate,\n type TemplateFormat,\n} from \"./template.js\";\nimport type { SerializedPromptTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport { MessageContent, ContentBlock } from \"../messages/index.js\";\n\n/**\n * Inputs to create a {@link PromptTemplate}\n * @augments BasePromptTemplateInput\n */\nexport interface PromptTemplateInput<\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 Format extends TemplateFormat = TemplateFormat,\n> extends BasePromptTemplateInput<RunInput, PartialVariableName> {\n /**\n * The prompt template\n */\n template: MessageContent;\n\n /**\n * The format of the prompt template. Options are \"f-string\" and \"mustache\"\n */\n templateFormat?: Format;\n\n /**\n * Whether or not to try validating the template on initialization\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n}\n\ntype NonAlphanumeric =\n | \" \"\n | \"\\t\"\n | \"\\n\"\n | \"\\r\"\n | '\"'\n | \"'\"\n | \"{\"\n | \"[\"\n | \"(\"\n | \"`\"\n | \":\"\n | \";\";\n\n/**\n * Recursive type to extract template parameters from a string.\n * @template T - The input string.\n * @template Result - The resulting array of extracted template parameters.\n */\ntype ExtractTemplateParamsRecursive<\n T extends string,\n Result extends string[] = [],\n> = T extends `${string}{${infer Param}}${infer Rest}`\n ? Param extends `${NonAlphanumeric}${string}`\n ? ExtractTemplateParamsRecursive<Rest, Result> // for non-template variables that look like template variables e.g. see https://github.com/langchain-ai/langchainjs/blob/main/langchain/src/chains/query_constructor/prompt.ts\n : ExtractTemplateParamsRecursive<Rest, [...Result, Param]>\n : Result;\n\nexport type ParamsFromFString<T extends string> = {\n [Key in\n | ExtractTemplateParamsRecursive<T>[number]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (string & Record<never, never>)]: any;\n};\n\nexport type ExtractedFStringParams<\n T extends string,\n RunInput extends InputValues = Symbol,\n> = RunInput extends Symbol ? ParamsFromFString<T> : RunInput;\n\n/**\n * Schema to represent a basic prompt for an LLM.\n * @augments BasePromptTemplate\n * @augments PromptTemplateInput\n *\n * @example\n * ```ts\n * import { PromptTemplate } from \"langchain/prompts\";\n *\n * const prompt = new PromptTemplate({\n * inputVariables: [\"foo\"],\n * template: \"Say {foo}\",\n * });\n * ```\n */\nexport class PromptTemplate<\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 BaseStringPromptTemplate<RunInput, PartialVariableName>\n implements PromptTemplateInput<RunInput, PartialVariableName>\n{\n static lc_name() {\n return \"PromptTemplate\";\n }\n\n template: MessageContent;\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n\n constructor(input: PromptTemplateInput<RunInput, PartialVariableName>) {\n super(input);\n // If input is mustache and validateTemplate is not defined, set it to false\n if (\n input.templateFormat === \"mustache\" &&\n input.validateTemplate === undefined\n ) {\n this.validateTemplate = false;\n }\n Object.assign(this, input);\n\n if (this.validateTemplate) {\n if (this.templateFormat === \"mustache\") {\n throw new Error(\"Mustache templates cannot be validated.\");\n }\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.template,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"prompt\" {\n return \"prompt\";\n }\n\n /**\n * Formats the prompt template with the provided values.\n * @param values The values to be used to format the prompt template.\n * @returns A promise that resolves to a string which is the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n return renderTemplate(\n this.template as string,\n this.templateFormat,\n allValues\n );\n }\n\n /**\n * Take examples in list format with prefix and suffix to create a prompt.\n *\n * Intended to be used a a way to dynamically create a prompt from examples.\n *\n * @param examples - List of examples to use in the prompt.\n * @param suffix - String to go after the list of examples. Should generally set up the user's input.\n * @param inputVariables - A list of variable names the final prompt template will expect\n * @param exampleSeparator - The separator to use in between examples\n * @param prefix - String that should go before any examples. Generally includes examples.\n *\n * @returns The final prompt template generated.\n */\n static fromExamples(\n examples: string[],\n suffix: string,\n inputVariables: string[],\n exampleSeparator = \"\\n\\n\",\n prefix = \"\"\n ) {\n const template = [prefix, ...examples, suffix].join(exampleSeparator);\n return new PromptTemplate({\n inputVariables,\n template,\n });\n }\n\n /**\n * Load prompt template from a template f-string\n */\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"f-string\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"mustache\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<InputValues>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput> | InputValues> {\n const { templateFormat = \"f-string\", ...rest } = options ?? {};\n const names = new Set<string>();\n parseTemplate(template, templateFormat).forEach((node) => {\n if (node.type === \"variable\") {\n names.add(node.name);\n }\n });\n\n return new PromptTemplate({\n // Rely on extracted types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputVariables: [...names] as any[],\n templateFormat,\n template,\n ...rest,\n });\n }\n\n /**\n * Partially applies values to the prompt template.\n * @param values The values to be partially applied to the prompt template.\n * @returns A new instance of PromptTemplate with the partially applied values.\n */\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n ) as Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | NewPartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new PromptTemplate<\n InputValues<\n Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>\n >\n >(promptDict);\n }\n\n serialize(): SerializedPromptTemplate {\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Cannot serialize a prompt template with an output parser\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n template: this.template,\n template_format: this.templateFormat,\n };\n }\n\n static async deserialize(\n data: SerializedPromptTemplate\n ): Promise<PromptTemplate> {\n if (!data.template) {\n throw new Error(\"Prompt template must have a template\");\n }\n const res = new PromptTemplate({\n inputVariables: data.input_variables,\n template: data.template,\n templateFormat: data.template_format,\n });\n return res;\n }\n\n // TODO(from file)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6GA,IAAa,iBAAb,MAAa,uBAMH,yBAEV;CACE,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA,iBAAiC;CAEjC,mBAAmB;;;;;;CAOnB;CAEA,YAAYA,OAA2D;EACrE,MAAM,MAAM;AAEZ,MACE,MAAM,mBAAmB,cACzB,MAAM,qBAAqB,QAE3B,KAAK,mBAAmB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AK,iBAAiB,OACxB,OAAM,IAAI,MACR;AAGJ,SAAO;GACL,OAAO,KAAK,gBAAgB;GAC5B,iBAAiB,KAAK;GACtB,UAAU,KAAK;GACf,iBAAiB,KAAK;EACvB;CACF;CAED,aAAa,YACXC,MACyB;AACzB,MAAI,CAAC,KAAK,SACR,OAAM,IAAI,MAAM;EAElB,MAAM,MAAM,IAAI,eAAe;GAC7B,gBAAgB,KAAK;GACrB,UAAU,KAAK;GACf,gBAAgB,KAAK;EACtB;AACD,SAAO;CACR;AAGF"}
|
|
1
|
+
{"version":3,"file":"prompt.js","names":["input: PromptTemplateInput<RunInput, PartialVariableName>","totalInputVariables: string[]","values: TypedPromptInputValues<RunInput>","examples: string[]","suffix: string","inputVariables: string[]","template: T","options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >","values: PartialValues<NewPartialVariableName>","data: SerializedPromptTemplate"],"sources":["../../src/prompts/prompt.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n checkValidTemplate,\n parseTemplate,\n renderTemplate,\n type TemplateFormat,\n} from \"./template.js\";\nimport type { SerializedPromptTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport { MessageContent, ContentBlock } from \"../messages/index.js\";\n\n/**\n * Inputs to create a {@link PromptTemplate}\n * @augments BasePromptTemplateInput\n */\nexport interface PromptTemplateInput<\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 Format extends TemplateFormat = TemplateFormat,\n> extends BasePromptTemplateInput<RunInput, PartialVariableName> {\n /**\n * The prompt template\n */\n template: MessageContent;\n\n /**\n * The format of the prompt template. Options are \"f-string\" and \"mustache\"\n */\n templateFormat?: Format;\n\n /**\n * Whether or not to try validating the template on initialization\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n}\n\ntype NonAlphanumeric =\n | \" \"\n | \"\\t\"\n | \"\\n\"\n | \"\\r\"\n | '\"'\n | \"'\"\n | \"{\"\n | \"[\"\n | \"(\"\n | \"`\"\n | \":\"\n | \";\";\n\n/**\n * Recursive type to extract template parameters from a string.\n * @template T - The input string.\n * @template Result - The resulting array of extracted template parameters.\n */\ntype ExtractTemplateParamsRecursive<\n T extends string,\n Result extends string[] = [],\n> = T extends `${string}{${infer Param}}${infer Rest}`\n ? Param extends `${NonAlphanumeric}${string}`\n ? ExtractTemplateParamsRecursive<Rest, Result> // for non-template variables that look like template variables e.g. see https://github.com/langchain-ai/langchainjs/blob/main/langchain/src/chains/query_constructor/prompt.ts\n : ExtractTemplateParamsRecursive<Rest, [...Result, Param]>\n : Result;\n\nexport type ParamsFromFString<T extends string> = {\n [Key in\n | ExtractTemplateParamsRecursive<T>[number]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (string & Record<never, never>)]: any;\n};\n\nexport type ExtractedFStringParams<\n T extends string,\n RunInput extends InputValues = Symbol,\n> = RunInput extends Symbol ? ParamsFromFString<T> : RunInput;\n\n/**\n * Schema to represent a basic prompt for an LLM.\n * @augments BasePromptTemplate\n * @augments PromptTemplateInput\n *\n * @example\n * ```ts\n * import { PromptTemplate } from \"langchain/prompts\";\n *\n * const prompt = new PromptTemplate({\n * inputVariables: [\"foo\"],\n * template: \"Say {foo}\",\n * });\n * ```\n */\nexport class PromptTemplate<\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 BaseStringPromptTemplate<RunInput, PartialVariableName>\n implements PromptTemplateInput<RunInput, PartialVariableName>\n{\n static lc_name() {\n return \"PromptTemplate\";\n }\n\n template: MessageContent;\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n\n constructor(input: PromptTemplateInput<RunInput, PartialVariableName>) {\n super(input);\n // If input is mustache and validateTemplate is not defined, set it to false\n if (\n input.templateFormat === \"mustache\" &&\n input.validateTemplate === undefined\n ) {\n this.validateTemplate = false;\n }\n Object.assign(this, input);\n\n if (this.validateTemplate) {\n if (this.templateFormat === \"mustache\") {\n throw new Error(\"Mustache templates cannot be validated.\");\n }\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.template,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"prompt\" {\n return \"prompt\";\n }\n\n /**\n * Formats the prompt template with the provided values.\n * @param values The values to be used to format the prompt template.\n * @returns A promise that resolves to a string which is the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n return renderTemplate(\n this.template as string,\n this.templateFormat,\n allValues\n );\n }\n\n /**\n * Take examples in list format with prefix and suffix to create a prompt.\n *\n * Intended to be used a a way to dynamically create a prompt from examples.\n *\n * @param examples - List of examples to use in the prompt.\n * @param suffix - String to go after the list of examples. Should generally set up the user's input.\n * @param inputVariables - A list of variable names the final prompt template will expect\n * @param exampleSeparator - The separator to use in between examples\n * @param prefix - String that should go before any examples. Generally includes examples.\n *\n * @returns The final prompt template generated.\n */\n static fromExamples(\n examples: string[],\n suffix: string,\n inputVariables: string[],\n exampleSeparator = \"\\n\\n\",\n prefix = \"\"\n ) {\n const template = [prefix, ...examples, suffix].join(exampleSeparator);\n return new PromptTemplate({\n inputVariables,\n template,\n });\n }\n\n /**\n * Load prompt template from a template f-string\n */\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"f-string\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"mustache\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<InputValues>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput> | InputValues> {\n const { templateFormat = \"f-string\", ...rest } = options ?? {};\n const names = new Set<string>();\n parseTemplate(template, templateFormat).forEach((node) => {\n if (node.type === \"variable\") {\n names.add(node.name);\n }\n });\n\n return new PromptTemplate({\n // Rely on extracted types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputVariables: [...names] as any[],\n templateFormat,\n template,\n ...rest,\n });\n }\n\n /**\n * Partially applies values to the prompt template.\n * @param values The values to be partially applied to the prompt template.\n * @returns A new instance of PromptTemplate with the partially applied values.\n */\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n ) as Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | NewPartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new PromptTemplate<\n InputValues<\n Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>\n >\n >(promptDict);\n }\n\n serialize(): SerializedPromptTemplate {\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Cannot serialize a prompt template with an output parser\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n template: this.template,\n template_format: this.templateFormat,\n };\n }\n\n static async deserialize(\n data: SerializedPromptTemplate\n ): Promise<PromptTemplate> {\n if (!data.template) {\n throw new Error(\"Prompt template must have a template\");\n }\n const res = new PromptTemplate({\n inputVariables: data.input_variables,\n template: data.template,\n templateFormat: data.template_format,\n });\n return res;\n }\n\n // TODO(from file)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6GA,IAAa,iBAAb,MAAa,uBAMH,yBAEV;CACE,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA,iBAAiC;CAEjC,mBAAmB;;;;;;CAOnB;CAEA,YAAYA,OAA2D;EACrE,MAAM,MAAM;AAEZ,MACE,MAAM,mBAAmB,cACzB,MAAM,qBAAqB,QAE3B,KAAK,mBAAmB;EAE1B,OAAO,OAAO,MAAM,MAAM;AAE1B,MAAI,KAAK,kBAAkB;AACzB,OAAI,KAAK,mBAAmB,WAC1B,OAAM,IAAI,MAAM;GAElB,IAAIC,sBAAgC,KAAK;AACzC,OAAI,KAAK,kBACP,sBAAsB,oBAAoB,OACxC,OAAO,KAAK,KAAK,iBAAiB,CACnC;GAEH,mBACE,KAAK,UACL,KAAK,gBACL,oBACD;EACF;CACF;CAED,iBAA2B;AACzB,SAAO;CACR;;;;;;CAOD,MAAM,OAAOC,QAA2D;EACtE,MAAM,YAAY,MAAM,KAAK,6BAA6B,OAAO;AACjE,SAAO,eACL,KAAK,UACL,KAAK,gBACL,UACD;CACF;;;;;;;;;;;;;;CAeD,OAAO,aACLC,UACAC,QACAC,gBACA,mBAAmB,QACnB,SAAS,IACT;EACA,MAAM,WAAW;GAAC;GAAQ,GAAG;GAAU;EAAO,EAAC,KAAK,iBAAiB;AACrE,SAAO,IAAI,eAAe;GACxB;GACA;EACD;CACF;CAsCD,OAAO,aAILC,UACAC,SAImE;EACnE,MAAM,EAAE,iBAAiB,WAAY,GAAG,MAAM,GAAG,WAAW,CAAE;EAC9D,MAAM,wBAAQ,IAAI;EAClB,cAAc,UAAU,eAAe,CAAC,QAAQ,CAAC,SAAS;AACxD,OAAI,KAAK,SAAS,YAChB,MAAM,IAAI,KAAK,KAAK;EAEvB,EAAC;AAEF,SAAO,IAAI,eAAe;GAGxB,gBAAgB,CAAC,GAAG,KAAM;GAC1B;GACA;GACA,GAAG;EACJ;CACF;;;;;;CAOD,MAAM,QACJC,QACA;EACA,MAAM,oBAAoB,KAAK,eAAe,OAC5C,CAAC,OAAO,EAAE,MAAM,QACjB;EACD,MAAM,sBAAsB;GAC1B,GAAI,KAAK,oBAAoB,CAAE;GAC/B,GAAG;EACJ;EACD,MAAM,aAAa;GACjB,GAAG;GACH,gBAAgB;GAChB,kBAAkB;EACnB;AACD,SAAO,IAAI,eAIT;CACH;CAED,YAAsC;AACpC,MAAI,KAAK,iBAAiB,OACxB,OAAM,IAAI,MACR;AAGJ,SAAO;GACL,OAAO,KAAK,gBAAgB;GAC5B,iBAAiB,KAAK;GACtB,UAAU,KAAK;GACf,iBAAiB,KAAK;EACvB;CACF;CAED,aAAa,YACXC,MACyB;AACzB,MAAI,CAAC,KAAK,SACR,OAAM,IAAI,MAAM;EAElB,MAAM,MAAM,IAAI,eAAe;GAC7B,gBAAgB,KAAK;GACrB,UAAU,KAAK;GACf,gBAAgB,KAAK;EACtB;AACD,SAAO;CACR;AAGF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"structured.cjs","names":["x: unknown","ChatPromptTemplate","input: StructuredPromptInput<RunInput, PartialVariableName>","coerceable: RunnableLike<ChatPromptValueInterface, NewRunOutput>","RunnableBinding","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
|
|
1
|
+
{"version":3,"file":"structured.cjs","names":["x: unknown","ChatPromptTemplate","input: StructuredPromptInput<RunInput, PartialVariableName>","coerceable: RunnableLike<ChatPromptValueInterface, NewRunOutput>","RunnableBinding","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,yBAMHC,gCAEV;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,IAAIC,6BAAgB;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"}
|
|
@@ -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,\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
|
|
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"}
|
|
@@ -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>,\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
|
|
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>,\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
|
|
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"}
|