UNPKG

@langchain/core

Version:
1 lines 12.2 kB
{"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,SA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