UNPKG

@langchain/core

Version:
1 lines 19 kB
{"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":";;;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