{"version":3,"file":"few_shot.cjs","names":["BaseStringPromptTemplate","renderTemplate","PromptTemplate","BaseChatPromptTemplate"],"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  // 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 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      // oxlint-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,8BACHA,eAAAA,yBAEV;CACE,kBAAkB;CAElB;CAEA;CAEA;CAEA,SAAS;CAET,mBAAmB;CAEnB,SAAS;CAET,iBAAiC;CAEjC,mBAAmB;CAEnB,YAAY,OAAmC;AAC7C,QAAM,MAAM;AACZ,SAAO,OAAO,MAAM,MAAM;AAE1B,MAAI,KAAK,aAAa,KAAA,KAAa,KAAK,oBAAoB,KAAA,EAC1D,OAAM,IAAI,MACR,mEACD;AAGH,MAAI,KAAK,aAAa,KAAA,KAAa,KAAK,oBAAoB,KAAA,EAC1D,OAAM,IAAI,MACR,8DACD;AAGH,MAAI,KAAK,kBAAkB;GACzB,IAAI,sBAAgC,KAAK;AACzC,OAAI,KAAK,iBACP,uBAAsB,oBAAoB,OACxC,OAAO,KAAK,KAAK,iBAAiB,CACnC;AAEH,oBAAA,mBACE,KAAK,SAAS,KAAK,QACnB,KAAK,gBACL,oBACD;;;CAIL,iBAA6B;AAC3B,SAAO;;CAGT,OAAO,UAAU;AACf,SAAO;;CAGT,MAAc,YACZ,gBACwB;AACxB,MAAI,KAAK,aAAa,KAAA,EACpB,QAAO,KAAK;AAEd,MAAI,KAAK,oBAAoB,KAAA,EAC3B,QAAO,KAAK,gBAAgB,eAAe,eAAe;AAG5D,QAAM,IAAI,MACR,8DACD;;CAGH,MAAM,QACJ,QACA;EACA,MAAM,oBAAoB,KAAK,eAAe,QAC3C,OAAO,EAAE,MAAM,QACjB;EACD,MAAM,sBAAsB;GAC1B,GAAI,KAAK,oBAAoB,EAAE;GAC/B,GAA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