UNPKG

@langchain/core

Version:
1 lines 11.8 kB
{"version":3,"file":"prompt.cjs","names":["BaseStringPromptTemplate","renderTemplate"],"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 // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // oxlint-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 // oxlint-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 // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // oxlint-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 as 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 // oxlint-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":";;;;;;;;;;;;;;;;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