@langchain/core 1.1.19 → 1.1.21
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 +14 -0
- package/dist/agents.d.cts.map +1 -1
- package/dist/callbacks/base.cjs.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/load/import_map.cjs +2 -0
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +2 -0
- package/dist/load/import_map.js.map +1 -1
- package/dist/load/serializable.cjs.map +1 -1
- package/dist/load/serializable.js.map +1 -1
- package/dist/memory.d.cts.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/ssrf.cjs +271 -0
- package/dist/utils/ssrf.cjs.map +1 -0
- package/dist/utils/ssrf.d.cts +52 -0
- package/dist/utils/ssrf.d.cts.map +1 -0
- package/dist/utils/ssrf.d.ts +52 -0
- package/dist/utils/ssrf.d.ts.map +1 -0
- package/dist/utils/ssrf.js +260 -0
- package/dist/utils/ssrf.js.map +1 -0
- 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 +14 -3
- package/utils/ssrf.cjs +1 -0
- package/utils/ssrf.d.cts +1 -0
- package/utils/ssrf.d.ts +1 -0
- package/utils/ssrf.js +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"structured.cjs","names":["BaseOutputParser","schema: T","schemas: S","z","toJsonSchema","text: string","interopParseAsync","OutputParserException","options?: JsonMarkdownFormatInstructionsOptions","schemaInput: JsonSchema7Type","type: string","type","description"],"sources":["../../src/output_parsers/structured.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport {\n BaseOutputParser,\n FormatInstructionsOptions,\n OutputParserException,\n} from \"./base.js\";\nimport {\n type InteropZodType,\n type InferInteropZodOutput,\n interopParseAsync,\n} from \"../utils/types/zod.js\";\nimport {\n toJsonSchema,\n type JsonSchema7Type,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"../utils/json_schema.js\";\n\nexport type JsonMarkdownStructuredOutputParserInput = {\n interpolationDepth?: number;\n};\n\nexport interface JsonMarkdownFormatInstructionsOptions\n extends FormatInstructionsOptions {\n interpolationDepth?: number;\n}\n\nexport class StructuredOutputParser<\n T extends InteropZodType,\n> extends BaseOutputParser<InferInteropZodOutput<T>> {\n static lc_name() {\n return \"StructuredOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"structured\"];\n\n toJSON() {\n return this.toJSONNotImplemented();\n }\n\n constructor(public schema: T) {\n super(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a Zod schema.\n * @param schema The Zod schema which the output should match\n * @returns A new instance of StructuredOutputParser.\n */\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a set of names and\n * descriptions.\n * @param schemas An object where each key is a name and each value is a description\n * @returns A new instance of StructuredOutputParser.\n */\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this(zodSchema);\n }\n\n /**\n * Returns a markdown code snippet with a JSON object formatted according\n * to the schema.\n * @param options Optional. The options for formatting the instructions\n * @returns A markdown code snippet with a JSON object formatted according to the schema.\n */\n getFormatInstructions(): string {\n return `You must format your output as a JSON value that adheres to a given \"JSON Schema\" instance.\n\n\"JSON Schema\" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example \"JSON Schema\" instance {{\"properties\": {{\"foo\": {{\"description\": \"a list of test words\", \"type\": \"array\", \"items\": {{\"type\": \"string\"}}}}}}, \"required\": [\"foo\"]}}\nwould match an object with one required property, \"foo\". The \"type\" property specifies \"foo\" must be an \"array\", and the \"description\" property semantically describes it as \"a list of test words\". The items within \"foo\" must be strings.\nThus, the object {{\"foo\": [\"bar\", \"baz\"]}} is a well-formatted instance of this example \"JSON Schema\". The object {{\"properties\": {{\"foo\": [\"bar\", \"baz\"]}}}} is not well-formatted.\n\nYour output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\\`\\`\\`json\n${JSON.stringify(toJsonSchema(this.schema))}\n\\`\\`\\`\n`;\n }\n\n /**\n * Parses the given text according to the schema.\n * @param text The text to parse\n * @returns The parsed output.\n */\n async parse(text: string): Promise<InferInteropZodOutput<T>> {\n try {\n const trimmedText = text.trim();\n\n const json =\n // first case: if back ticks appear at the start of the text\n trimmedText.match(/^```(?:json)?\\s*([\\s\\S]*?)```/)?.[1] ||\n // second case: if back ticks with `json` appear anywhere in the text\n trimmedText.match(/```json\\s*([\\s\\S]*?)```/)?.[1] ||\n // otherwise, return the trimmed text\n trimmedText;\n\n const escapedJson = json\n .replace(/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/g, (_match, capturedGroup) => {\n const escapedInsideQuotes = capturedGroup.replace(/\\n/g, \"\\\\n\");\n return `\"${escapedInsideQuotes}\"`;\n })\n .replace(/\\n/g, \"\");\n\n return await interopParseAsync(this.schema, JSON.parse(escapedJson));\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n }\n}\n\n/**\n * A specific type of `StructuredOutputParser` that parses JSON data\n * formatted as a markdown code snippet.\n */\nexport class JsonMarkdownStructuredOutputParser<\n T extends InteropZodType,\n> extends StructuredOutputParser<T> {\n static lc_name() {\n return \"JsonMarkdownStructuredOutputParser\";\n }\n\n getFormatInstructions(\n options?: JsonMarkdownFormatInstructionsOptions\n ): string {\n const interpolationDepth = options?.interpolationDepth ?? 1;\n if (interpolationDepth < 1) {\n throw new Error(\"f string interpolation depth must be at least 1\");\n }\n\n return `Return a markdown code snippet with a JSON object formatted to look like:\\n\\`\\`\\`json\\n${this._schemaToInstruction(\n toJsonSchema(this.schema)\n )\n .replaceAll(\"{\", \"{\".repeat(interpolationDepth))\n .replaceAll(\"}\", \"}\".repeat(interpolationDepth))}\\n\\`\\`\\``;\n }\n\n private _schemaToInstruction(\n schemaInput: JsonSchema7Type,\n indent = 2\n ): string {\n const schema = schemaInput as Extract<\n JsonSchema7Type,\n | JsonSchema7ObjectType\n | JsonSchema7ArrayType\n | JsonSchema7StringType\n | JsonSchema7NumberType\n | JsonSchema7NullableType\n >;\n\n if (\"type\" in schema) {\n let nullable = false;\n let type: string;\n if (Array.isArray(schema.type)) {\n const nullIdx = schema.type.findIndex((type) => type === \"null\");\n if (nullIdx !== -1) {\n nullable = true;\n schema.type.splice(nullIdx, 1);\n }\n type = schema.type.join(\" | \") as string;\n } else {\n type = schema.type;\n }\n\n if (schema.type === \"object\" && schema.properties) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n const properties = Object.entries(schema.properties)\n .map(([key, value]) => {\n const isOptional = schema.required?.includes(key)\n ? \"\"\n : \" (optional)\";\n return `${\" \".repeat(indent)}\"${key}\": ${this._schemaToInstruction(\n value,\n indent + 2\n )}${isOptional}`;\n })\n .join(\"\\n\");\n return `{\\n${properties}\\n${\" \".repeat(indent - 2)}}${description}`;\n }\n if (schema.type === \"array\" && schema.items) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n return `array[\\n${\" \".repeat(indent)}${this._schemaToInstruction(\n schema.items,\n indent + 2\n )}\\n${\" \".repeat(indent - 2)}] ${description}`;\n }\n const isNullable = nullable ? \" (nullable)\" : \"\";\n const description = schema.description ? ` // ${schema.description}` : \"\";\n return `${type}${description}${isNullable}`;\n }\n\n if (\"anyOf\" in schema) {\n return schema.anyOf\n .map((s) => this._schemaToInstruction(s, indent))\n .join(`\\n${\" \".repeat(indent - 2)}`);\n }\n\n throw new Error(\"unsupported schema type\");\n }\n\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this<T>(schema);\n }\n\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this<typeof zodSchema>(zodSchema);\n }\n}\n\nexport interface AsymmetricStructuredOutputParserFields<\n T extends InteropZodType,\n> {\n inputSchema: T;\n}\n\n/**\n * A type of `StructuredOutputParser` that handles asymmetric input and\n * output schemas.\n */\nexport abstract class AsymmetricStructuredOutputParser<\n T extends InteropZodType,\n Y = unknown,\n> extends BaseOutputParser<Y> {\n private structuredInputParser: JsonMarkdownStructuredOutputParser<T>;\n\n constructor({ inputSchema }: AsymmetricStructuredOutputParserFields<T>) {\n super(...arguments);\n this.structuredInputParser = new JsonMarkdownStructuredOutputParser(\n inputSchema\n );\n }\n\n /**\n * Processes the parsed input into the desired output format. Must be\n * implemented by subclasses.\n * @param input The parsed input\n * @returns The processed output.\n */\n abstract outputProcessor(input: InferInteropZodOutput<T>): Promise<Y>;\n\n async parse(text: string): Promise<Y> {\n let parsedInput;\n try {\n parsedInput = await this.structuredInputParser.parse(text);\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n\n return this.outputProcessor(parsedInput);\n }\n\n getFormatInstructions(): string {\n return this.structuredInputParser.getFormatInstructions();\n }\n}\n"],"mappings":";;;;;;;AA8BA,IAAa,yBAAb,cAEUA,8BAA2C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.cjs","names":["BaseOutputParser","schema: T","schemas: S","z","toJsonSchema","text: string","interopParseAsync","OutputParserException","options?: JsonMarkdownFormatInstructionsOptions","schemaInput: JsonSchema7Type","type: string","type","description"],"sources":["../../src/output_parsers/structured.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport {\n BaseOutputParser,\n FormatInstructionsOptions,\n OutputParserException,\n} from \"./base.js\";\nimport {\n type InteropZodType,\n type InferInteropZodOutput,\n interopParseAsync,\n} from \"../utils/types/zod.js\";\nimport {\n toJsonSchema,\n type JsonSchema7Type,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"../utils/json_schema.js\";\n\nexport type JsonMarkdownStructuredOutputParserInput = {\n interpolationDepth?: number;\n};\n\nexport interface JsonMarkdownFormatInstructionsOptions extends FormatInstructionsOptions {\n interpolationDepth?: number;\n}\n\nexport class StructuredOutputParser<\n T extends InteropZodType,\n> extends BaseOutputParser<InferInteropZodOutput<T>> {\n static lc_name() {\n return \"StructuredOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"structured\"];\n\n toJSON() {\n return this.toJSONNotImplemented();\n }\n\n constructor(public schema: T) {\n super(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a Zod schema.\n * @param schema The Zod schema which the output should match\n * @returns A new instance of StructuredOutputParser.\n */\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a set of names and\n * descriptions.\n * @param schemas An object where each key is a name and each value is a description\n * @returns A new instance of StructuredOutputParser.\n */\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this(zodSchema);\n }\n\n /**\n * Returns a markdown code snippet with a JSON object formatted according\n * to the schema.\n * @param options Optional. The options for formatting the instructions\n * @returns A markdown code snippet with a JSON object formatted according to the schema.\n */\n getFormatInstructions(): string {\n return `You must format your output as a JSON value that adheres to a given \"JSON Schema\" instance.\n\n\"JSON Schema\" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example \"JSON Schema\" instance {{\"properties\": {{\"foo\": {{\"description\": \"a list of test words\", \"type\": \"array\", \"items\": {{\"type\": \"string\"}}}}}}, \"required\": [\"foo\"]}}\nwould match an object with one required property, \"foo\". The \"type\" property specifies \"foo\" must be an \"array\", and the \"description\" property semantically describes it as \"a list of test words\". The items within \"foo\" must be strings.\nThus, the object {{\"foo\": [\"bar\", \"baz\"]}} is a well-formatted instance of this example \"JSON Schema\". The object {{\"properties\": {{\"foo\": [\"bar\", \"baz\"]}}}} is not well-formatted.\n\nYour output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\\`\\`\\`json\n${JSON.stringify(toJsonSchema(this.schema))}\n\\`\\`\\`\n`;\n }\n\n /**\n * Parses the given text according to the schema.\n * @param text The text to parse\n * @returns The parsed output.\n */\n async parse(text: string): Promise<InferInteropZodOutput<T>> {\n try {\n const trimmedText = text.trim();\n\n const json =\n // first case: if back ticks appear at the start of the text\n trimmedText.match(/^```(?:json)?\\s*([\\s\\S]*?)```/)?.[1] ||\n // second case: if back ticks with `json` appear anywhere in the text\n trimmedText.match(/```json\\s*([\\s\\S]*?)```/)?.[1] ||\n // otherwise, return the trimmed text\n trimmedText;\n\n const escapedJson = json\n .replace(/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/g, (_match, capturedGroup) => {\n const escapedInsideQuotes = capturedGroup.replace(/\\n/g, \"\\\\n\");\n return `\"${escapedInsideQuotes}\"`;\n })\n .replace(/\\n/g, \"\");\n\n return await interopParseAsync(this.schema, JSON.parse(escapedJson));\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n }\n}\n\n/**\n * A specific type of `StructuredOutputParser` that parses JSON data\n * formatted as a markdown code snippet.\n */\nexport class JsonMarkdownStructuredOutputParser<\n T extends InteropZodType,\n> extends StructuredOutputParser<T> {\n static lc_name() {\n return \"JsonMarkdownStructuredOutputParser\";\n }\n\n getFormatInstructions(\n options?: JsonMarkdownFormatInstructionsOptions\n ): string {\n const interpolationDepth = options?.interpolationDepth ?? 1;\n if (interpolationDepth < 1) {\n throw new Error(\"f string interpolation depth must be at least 1\");\n }\n\n return `Return a markdown code snippet with a JSON object formatted to look like:\\n\\`\\`\\`json\\n${this._schemaToInstruction(\n toJsonSchema(this.schema)\n )\n .replaceAll(\"{\", \"{\".repeat(interpolationDepth))\n .replaceAll(\"}\", \"}\".repeat(interpolationDepth))}\\n\\`\\`\\``;\n }\n\n private _schemaToInstruction(\n schemaInput: JsonSchema7Type,\n indent = 2\n ): string {\n const schema = schemaInput as Extract<\n JsonSchema7Type,\n | JsonSchema7ObjectType\n | JsonSchema7ArrayType\n | JsonSchema7StringType\n | JsonSchema7NumberType\n | JsonSchema7NullableType\n >;\n\n if (\"type\" in schema) {\n let nullable = false;\n let type: string;\n if (Array.isArray(schema.type)) {\n const nullIdx = schema.type.findIndex((type) => type === \"null\");\n if (nullIdx !== -1) {\n nullable = true;\n schema.type.splice(nullIdx, 1);\n }\n type = schema.type.join(\" | \") as string;\n } else {\n type = schema.type;\n }\n\n if (schema.type === \"object\" && schema.properties) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n const properties = Object.entries(schema.properties)\n .map(([key, value]) => {\n const isOptional = schema.required?.includes(key)\n ? \"\"\n : \" (optional)\";\n return `${\" \".repeat(indent)}\"${key}\": ${this._schemaToInstruction(\n value,\n indent + 2\n )}${isOptional}`;\n })\n .join(\"\\n\");\n return `{\\n${properties}\\n${\" \".repeat(indent - 2)}}${description}`;\n }\n if (schema.type === \"array\" && schema.items) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n return `array[\\n${\" \".repeat(indent)}${this._schemaToInstruction(\n schema.items,\n indent + 2\n )}\\n${\" \".repeat(indent - 2)}] ${description}`;\n }\n const isNullable = nullable ? \" (nullable)\" : \"\";\n const description = schema.description ? ` // ${schema.description}` : \"\";\n return `${type}${description}${isNullable}`;\n }\n\n if (\"anyOf\" in schema) {\n return schema.anyOf\n .map((s) => this._schemaToInstruction(s, indent))\n .join(`\\n${\" \".repeat(indent - 2)}`);\n }\n\n throw new Error(\"unsupported schema type\");\n }\n\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this<T>(schema);\n }\n\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this<typeof zodSchema>(zodSchema);\n }\n}\n\nexport interface AsymmetricStructuredOutputParserFields<\n T extends InteropZodType,\n> {\n inputSchema: T;\n}\n\n/**\n * A type of `StructuredOutputParser` that handles asymmetric input and\n * output schemas.\n */\nexport abstract class AsymmetricStructuredOutputParser<\n T extends InteropZodType,\n Y = unknown,\n> extends BaseOutputParser<Y> {\n private structuredInputParser: JsonMarkdownStructuredOutputParser<T>;\n\n constructor({ inputSchema }: AsymmetricStructuredOutputParserFields<T>) {\n super(...arguments);\n this.structuredInputParser = new JsonMarkdownStructuredOutputParser(\n inputSchema\n );\n }\n\n /**\n * Processes the parsed input into the desired output format. Must be\n * implemented by subclasses.\n * @param input The parsed input\n * @returns The processed output.\n */\n abstract outputProcessor(input: InferInteropZodOutput<T>): Promise<Y>;\n\n async parse(text: string): Promise<Y> {\n let parsedInput;\n try {\n parsedInput = await this.structuredInputParser.parse(text);\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n\n return this.outputProcessor(parsedInput);\n }\n\n getFormatInstructions(): string {\n return this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AAgC;AAC9B,SAAO,KAAK,sBAAsB,uBAAuB;CAC1D;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"structured.js","names":["schema: T","schemas: S","text: string","options?: JsonMarkdownFormatInstructionsOptions","schemaInput: JsonSchema7Type","type: string","type","description"],"sources":["../../src/output_parsers/structured.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport {\n BaseOutputParser,\n FormatInstructionsOptions,\n OutputParserException,\n} from \"./base.js\";\nimport {\n type InteropZodType,\n type InferInteropZodOutput,\n interopParseAsync,\n} from \"../utils/types/zod.js\";\nimport {\n toJsonSchema,\n type JsonSchema7Type,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"../utils/json_schema.js\";\n\nexport type JsonMarkdownStructuredOutputParserInput = {\n interpolationDepth?: number;\n};\n\nexport interface JsonMarkdownFormatInstructionsOptions\n extends FormatInstructionsOptions {\n interpolationDepth?: number;\n}\n\nexport class StructuredOutputParser<\n T extends InteropZodType,\n> extends BaseOutputParser<InferInteropZodOutput<T>> {\n static lc_name() {\n return \"StructuredOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"structured\"];\n\n toJSON() {\n return this.toJSONNotImplemented();\n }\n\n constructor(public schema: T) {\n super(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a Zod schema.\n * @param schema The Zod schema which the output should match\n * @returns A new instance of StructuredOutputParser.\n */\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a set of names and\n * descriptions.\n * @param schemas An object where each key is a name and each value is a description\n * @returns A new instance of StructuredOutputParser.\n */\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this(zodSchema);\n }\n\n /**\n * Returns a markdown code snippet with a JSON object formatted according\n * to the schema.\n * @param options Optional. The options for formatting the instructions\n * @returns A markdown code snippet with a JSON object formatted according to the schema.\n */\n getFormatInstructions(): string {\n return `You must format your output as a JSON value that adheres to a given \"JSON Schema\" instance.\n\n\"JSON Schema\" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example \"JSON Schema\" instance {{\"properties\": {{\"foo\": {{\"description\": \"a list of test words\", \"type\": \"array\", \"items\": {{\"type\": \"string\"}}}}}}, \"required\": [\"foo\"]}}\nwould match an object with one required property, \"foo\". The \"type\" property specifies \"foo\" must be an \"array\", and the \"description\" property semantically describes it as \"a list of test words\". The items within \"foo\" must be strings.\nThus, the object {{\"foo\": [\"bar\", \"baz\"]}} is a well-formatted instance of this example \"JSON Schema\". The object {{\"properties\": {{\"foo\": [\"bar\", \"baz\"]}}}} is not well-formatted.\n\nYour output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\\`\\`\\`json\n${JSON.stringify(toJsonSchema(this.schema))}\n\\`\\`\\`\n`;\n }\n\n /**\n * Parses the given text according to the schema.\n * @param text The text to parse\n * @returns The parsed output.\n */\n async parse(text: string): Promise<InferInteropZodOutput<T>> {\n try {\n const trimmedText = text.trim();\n\n const json =\n // first case: if back ticks appear at the start of the text\n trimmedText.match(/^```(?:json)?\\s*([\\s\\S]*?)```/)?.[1] ||\n // second case: if back ticks with `json` appear anywhere in the text\n trimmedText.match(/```json\\s*([\\s\\S]*?)```/)?.[1] ||\n // otherwise, return the trimmed text\n trimmedText;\n\n const escapedJson = json\n .replace(/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/g, (_match, capturedGroup) => {\n const escapedInsideQuotes = capturedGroup.replace(/\\n/g, \"\\\\n\");\n return `\"${escapedInsideQuotes}\"`;\n })\n .replace(/\\n/g, \"\");\n\n return await interopParseAsync(this.schema, JSON.parse(escapedJson));\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n }\n}\n\n/**\n * A specific type of `StructuredOutputParser` that parses JSON data\n * formatted as a markdown code snippet.\n */\nexport class JsonMarkdownStructuredOutputParser<\n T extends InteropZodType,\n> extends StructuredOutputParser<T> {\n static lc_name() {\n return \"JsonMarkdownStructuredOutputParser\";\n }\n\n getFormatInstructions(\n options?: JsonMarkdownFormatInstructionsOptions\n ): string {\n const interpolationDepth = options?.interpolationDepth ?? 1;\n if (interpolationDepth < 1) {\n throw new Error(\"f string interpolation depth must be at least 1\");\n }\n\n return `Return a markdown code snippet with a JSON object formatted to look like:\\n\\`\\`\\`json\\n${this._schemaToInstruction(\n toJsonSchema(this.schema)\n )\n .replaceAll(\"{\", \"{\".repeat(interpolationDepth))\n .replaceAll(\"}\", \"}\".repeat(interpolationDepth))}\\n\\`\\`\\``;\n }\n\n private _schemaToInstruction(\n schemaInput: JsonSchema7Type,\n indent = 2\n ): string {\n const schema = schemaInput as Extract<\n JsonSchema7Type,\n | JsonSchema7ObjectType\n | JsonSchema7ArrayType\n | JsonSchema7StringType\n | JsonSchema7NumberType\n | JsonSchema7NullableType\n >;\n\n if (\"type\" in schema) {\n let nullable = false;\n let type: string;\n if (Array.isArray(schema.type)) {\n const nullIdx = schema.type.findIndex((type) => type === \"null\");\n if (nullIdx !== -1) {\n nullable = true;\n schema.type.splice(nullIdx, 1);\n }\n type = schema.type.join(\" | \") as string;\n } else {\n type = schema.type;\n }\n\n if (schema.type === \"object\" && schema.properties) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n const properties = Object.entries(schema.properties)\n .map(([key, value]) => {\n const isOptional = schema.required?.includes(key)\n ? \"\"\n : \" (optional)\";\n return `${\" \".repeat(indent)}\"${key}\": ${this._schemaToInstruction(\n value,\n indent + 2\n )}${isOptional}`;\n })\n .join(\"\\n\");\n return `{\\n${properties}\\n${\" \".repeat(indent - 2)}}${description}`;\n }\n if (schema.type === \"array\" && schema.items) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n return `array[\\n${\" \".repeat(indent)}${this._schemaToInstruction(\n schema.items,\n indent + 2\n )}\\n${\" \".repeat(indent - 2)}] ${description}`;\n }\n const isNullable = nullable ? \" (nullable)\" : \"\";\n const description = schema.description ? ` // ${schema.description}` : \"\";\n return `${type}${description}${isNullable}`;\n }\n\n if (\"anyOf\" in schema) {\n return schema.anyOf\n .map((s) => this._schemaToInstruction(s, indent))\n .join(`\\n${\" \".repeat(indent - 2)}`);\n }\n\n throw new Error(\"unsupported schema type\");\n }\n\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this<T>(schema);\n }\n\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this<typeof zodSchema>(zodSchema);\n }\n}\n\nexport interface AsymmetricStructuredOutputParserFields<\n T extends InteropZodType,\n> {\n inputSchema: T;\n}\n\n/**\n * A type of `StructuredOutputParser` that handles asymmetric input and\n * output schemas.\n */\nexport abstract class AsymmetricStructuredOutputParser<\n T extends InteropZodType,\n Y = unknown,\n> extends BaseOutputParser<Y> {\n private structuredInputParser: JsonMarkdownStructuredOutputParser<T>;\n\n constructor({ inputSchema }: AsymmetricStructuredOutputParserFields<T>) {\n super(...arguments);\n this.structuredInputParser = new JsonMarkdownStructuredOutputParser(\n inputSchema\n );\n }\n\n /**\n * Processes the parsed input into the desired output format. Must be\n * implemented by subclasses.\n * @param input The parsed input\n * @returns The processed output.\n */\n abstract outputProcessor(input: InferInteropZodOutput<T>): Promise<Y>;\n\n async parse(text: string): Promise<Y> {\n let parsedInput;\n try {\n parsedInput = await this.structuredInputParser.parse(text);\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n\n return this.outputProcessor(parsedInput);\n }\n\n getFormatInstructions(): string {\n return this.structuredInputParser.getFormatInstructions();\n }\n}\n"],"mappings":";;;;;;AA8BA,IAAa,yBAAb,cAEU,iBAA2C;CACnD,OAAO,UAAU;AACf,SAAO;CACR;CAED,eAAe;EAAC;EAAa;EAAkB;CAAa;CAE5D,SAAS;AACP,SAAO,KAAK,sBAAsB;CACnC;CAED,YAAmBA,QAAW;EAC5B,MAAM,OAAO;EADI;CAElB;;;;;;CAOD,OAAO,cAAwCA,QAAW;AACxD,SAAO,IAAI,KAAK;CACjB;;;;;;;CAQD,OAAO,yBACLC,SACA;EACA,MAAM,YAAY,EAAE,OAClB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,IACtB,CAAC,CAAC,MAAM,YAAY,KAClB,CAAC,MAAM,EAAE,QAAQ,CAAC,SAAS,YAAY,AAAC,EAC3C,CACF,CACF;AAED,SAAO,IAAI,KAAK;CACjB;;;;;;;CAQD,wBAAgC;AAC9B,SAAO,CAAC;;;;;;;;;;;;AAYZ,EAAE,KAAK,UAAU,aAAa,KAAK,OAAO,CAAC,CAAC;;AAE5C,CAAC;CACE;;;;;;CAOD,MAAM,MAAMC,MAAiD;AAC3D,MAAI;GACF,MAAM,cAAc,KAAK,MAAM;GAE/B,MAAM,OAEJ,YAAY,MAAM,gCAAgC,GAAG,MAErD,YAAY,MAAM,0BAA0B,GAAG,MAE/C;GAEF,MAAM,cAAc,KACjB,QAAQ,6BAA6B,CAAC,QAAQ,kBAAkB;IAC/D,MAAM,sBAAsB,cAAc,QAAQ,OAAO,MAAM;AAC/D,WAAO,CAAC,CAAC,EAAE,oBAAoB,CAAC,CAAC;GAClC,EAAC,CACD,QAAQ,OAAO,GAAG;AAErB,UAAO,MAAM,kBAAkB,KAAK,QAAQ,KAAK,MAAM,YAAY,CAAC;EACrE,SAAQ,GAAG;AACV,SAAM,IAAI,sBACR,CAAC,wBAAwB,EAAE,KAAK,UAAU,EAAE,G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;AAED,SAAO,KAAK,gBAAgB,YAAY;CACzC;CAED,wBAAgC;AAC9B,SAAO,KAAK,sBAAsB,uBAAuB;CAC1D;AACF"}
|
|
1
|
+
{"version":3,"file":"structured.js","names":["schema: T","schemas: S","text: string","options?: JsonMarkdownFormatInstructionsOptions","schemaInput: JsonSchema7Type","type: string","type","description"],"sources":["../../src/output_parsers/structured.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport {\n BaseOutputParser,\n FormatInstructionsOptions,\n OutputParserException,\n} from \"./base.js\";\nimport {\n type InteropZodType,\n type InferInteropZodOutput,\n interopParseAsync,\n} from \"../utils/types/zod.js\";\nimport {\n toJsonSchema,\n type JsonSchema7Type,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"../utils/json_schema.js\";\n\nexport type JsonMarkdownStructuredOutputParserInput = {\n interpolationDepth?: number;\n};\n\nexport interface JsonMarkdownFormatInstructionsOptions extends FormatInstructionsOptions {\n interpolationDepth?: number;\n}\n\nexport class StructuredOutputParser<\n T extends InteropZodType,\n> extends BaseOutputParser<InferInteropZodOutput<T>> {\n static lc_name() {\n return \"StructuredOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"structured\"];\n\n toJSON() {\n return this.toJSONNotImplemented();\n }\n\n constructor(public schema: T) {\n super(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a Zod schema.\n * @param schema The Zod schema which the output should match\n * @returns A new instance of StructuredOutputParser.\n */\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this(schema);\n }\n\n /**\n * Creates a new StructuredOutputParser from a set of names and\n * descriptions.\n * @param schemas An object where each key is a name and each value is a description\n * @returns A new instance of StructuredOutputParser.\n */\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this(zodSchema);\n }\n\n /**\n * Returns a markdown code snippet with a JSON object formatted according\n * to the schema.\n * @param options Optional. The options for formatting the instructions\n * @returns A markdown code snippet with a JSON object formatted according to the schema.\n */\n getFormatInstructions(): string {\n return `You must format your output as a JSON value that adheres to a given \"JSON Schema\" instance.\n\n\"JSON Schema\" is a declarative language that allows you to annotate and validate JSON documents.\n\nFor example, the example \"JSON Schema\" instance {{\"properties\": {{\"foo\": {{\"description\": \"a list of test words\", \"type\": \"array\", \"items\": {{\"type\": \"string\"}}}}}}, \"required\": [\"foo\"]}}\nwould match an object with one required property, \"foo\". The \"type\" property specifies \"foo\" must be an \"array\", and the \"description\" property semantically describes it as \"a list of test words\". The items within \"foo\" must be strings.\nThus, the object {{\"foo\": [\"bar\", \"baz\"]}} is a well-formatted instance of this example \"JSON Schema\". The object {{\"properties\": {{\"foo\": [\"bar\", \"baz\"]}}}} is not well-formatted.\n\nYour output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!\n\nHere is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:\n\\`\\`\\`json\n${JSON.stringify(toJsonSchema(this.schema))}\n\\`\\`\\`\n`;\n }\n\n /**\n * Parses the given text according to the schema.\n * @param text The text to parse\n * @returns The parsed output.\n */\n async parse(text: string): Promise<InferInteropZodOutput<T>> {\n try {\n const trimmedText = text.trim();\n\n const json =\n // first case: if back ticks appear at the start of the text\n trimmedText.match(/^```(?:json)?\\s*([\\s\\S]*?)```/)?.[1] ||\n // second case: if back ticks with `json` appear anywhere in the text\n trimmedText.match(/```json\\s*([\\s\\S]*?)```/)?.[1] ||\n // otherwise, return the trimmed text\n trimmedText;\n\n const escapedJson = json\n .replace(/\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/g, (_match, capturedGroup) => {\n const escapedInsideQuotes = capturedGroup.replace(/\\n/g, \"\\\\n\");\n return `\"${escapedInsideQuotes}\"`;\n })\n .replace(/\\n/g, \"\");\n\n return await interopParseAsync(this.schema, JSON.parse(escapedJson));\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n }\n}\n\n/**\n * A specific type of `StructuredOutputParser` that parses JSON data\n * formatted as a markdown code snippet.\n */\nexport class JsonMarkdownStructuredOutputParser<\n T extends InteropZodType,\n> extends StructuredOutputParser<T> {\n static lc_name() {\n return \"JsonMarkdownStructuredOutputParser\";\n }\n\n getFormatInstructions(\n options?: JsonMarkdownFormatInstructionsOptions\n ): string {\n const interpolationDepth = options?.interpolationDepth ?? 1;\n if (interpolationDepth < 1) {\n throw new Error(\"f string interpolation depth must be at least 1\");\n }\n\n return `Return a markdown code snippet with a JSON object formatted to look like:\\n\\`\\`\\`json\\n${this._schemaToInstruction(\n toJsonSchema(this.schema)\n )\n .replaceAll(\"{\", \"{\".repeat(interpolationDepth))\n .replaceAll(\"}\", \"}\".repeat(interpolationDepth))}\\n\\`\\`\\``;\n }\n\n private _schemaToInstruction(\n schemaInput: JsonSchema7Type,\n indent = 2\n ): string {\n const schema = schemaInput as Extract<\n JsonSchema7Type,\n | JsonSchema7ObjectType\n | JsonSchema7ArrayType\n | JsonSchema7StringType\n | JsonSchema7NumberType\n | JsonSchema7NullableType\n >;\n\n if (\"type\" in schema) {\n let nullable = false;\n let type: string;\n if (Array.isArray(schema.type)) {\n const nullIdx = schema.type.findIndex((type) => type === \"null\");\n if (nullIdx !== -1) {\n nullable = true;\n schema.type.splice(nullIdx, 1);\n }\n type = schema.type.join(\" | \") as string;\n } else {\n type = schema.type;\n }\n\n if (schema.type === \"object\" && schema.properties) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n const properties = Object.entries(schema.properties)\n .map(([key, value]) => {\n const isOptional = schema.required?.includes(key)\n ? \"\"\n : \" (optional)\";\n return `${\" \".repeat(indent)}\"${key}\": ${this._schemaToInstruction(\n value,\n indent + 2\n )}${isOptional}`;\n })\n .join(\"\\n\");\n return `{\\n${properties}\\n${\" \".repeat(indent - 2)}}${description}`;\n }\n if (schema.type === \"array\" && schema.items) {\n const description = schema.description\n ? ` // ${schema.description}`\n : \"\";\n return `array[\\n${\" \".repeat(indent)}${this._schemaToInstruction(\n schema.items,\n indent + 2\n )}\\n${\" \".repeat(indent - 2)}] ${description}`;\n }\n const isNullable = nullable ? \" (nullable)\" : \"\";\n const description = schema.description ? ` // ${schema.description}` : \"\";\n return `${type}${description}${isNullable}`;\n }\n\n if (\"anyOf\" in schema) {\n return schema.anyOf\n .map((s) => this._schemaToInstruction(s, indent))\n .join(`\\n${\" \".repeat(indent - 2)}`);\n }\n\n throw new Error(\"unsupported schema type\");\n }\n\n static fromZodSchema<T extends InteropZodType>(schema: T) {\n return new this<T>(schema);\n }\n\n static fromNamesAndDescriptions<S extends { [key: string]: string }>(\n schemas: S\n ) {\n const zodSchema = z.object(\n Object.fromEntries(\n Object.entries(schemas).map(\n ([name, description]) =>\n [name, z.string().describe(description)] as const\n )\n )\n );\n\n return new this<typeof zodSchema>(zodSchema);\n }\n}\n\nexport interface AsymmetricStructuredOutputParserFields<\n T extends InteropZodType,\n> {\n inputSchema: T;\n}\n\n/**\n * A type of `StructuredOutputParser` that handles asymmetric input and\n * output schemas.\n */\nexport abstract class AsymmetricStructuredOutputParser<\n T extends InteropZodType,\n Y = unknown,\n> extends BaseOutputParser<Y> {\n private structuredInputParser: JsonMarkdownStructuredOutputParser<T>;\n\n constructor({ inputSchema }: AsymmetricStructuredOutputParserFields<T>) {\n super(...arguments);\n this.structuredInputParser = new JsonMarkdownStructuredOutputParser(\n inputSchema\n );\n }\n\n /**\n * Processes the parsed input into the desired output format. Must be\n * implemented by subclasses.\n * @param input The parsed input\n * @returns The processed output.\n */\n abstract outputProcessor(input: InferInteropZodOutput<T>): Promise<Y>;\n\n async parse(text: string): Promise<Y> {\n let parsedInput;\n try {\n parsedInput = await this.structuredInputParser.parse(text);\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n\n return this.outputProcessor(parsedInput);\n }\n\n getFormatInstructions(): string {\n return this.structuredInputParser.getFormatInstructions();\n }\n}\n"],"mappings":";;;;;;AA6BA,IAAa,yBAAb,cAEU,iBAA2C;CACnD,OAAO,UAAU;AACf,SAAO;CACR;CAED,eAAe;EAAC;EAAa;EAAkB;CAAa;CAE5D,SAAS;AACP,SAAO,KAAK,sBAAsB;CACnC;CAED,YAAmBA,QAAW;EAC5B,MAAM,OAAO;EADI;CAElB;;;;;;CAOD,OAAO,cAAwCA,QAAW;AACxD,SAAO,IAAI,KAAK;CACjB;;;;;;;CAQD,OAAO,yBACLC,SACA;EACA,MAAM,YAAY,EAAE,OAClB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,IACtB,CAAC,CAAC,MAAM,YAAY,KAClB,CAAC,MAAM,EAAE,QAAQ,CAAC,SAAS,YAAY,AAAC,EAC3C,CACF,CACF;AAED,SAAO,IAAI,KAAK;CACjB;;;;;;;CAQD,wBAAgC;AAC9B,SAAO,CAAC;;;;;;;;;;;;AAYZ,EAAE,KAAK,UAAU,aAAa,KAAK,OAAO,CAAC,CAAC;;AAE5C,CAAC;CACE;;;;;;CAOD,MAAM,MAAMC,MAAiD;AAC3D,MAAI;GACF,MAAM,cAAc,KAAK,MAAM;GAE/B,MAAM,OAEJ,YAAY,MAAM,gCAAgC,GAAG,MAErD,YAAY,MAAM,0BAA0B,GAAG,MAE/C;GAEF,MAAM,cAAc,KACjB,QAAQ,6BAA6B,CAAC,QAAQ,kBAAkB;IAC/D,MAAM,sBAAsB,cAAc,QAAQ,OAAO,MAAM;AAC/D,WAAO,CAAC,CAAC,EAAE,oBAAoB,CAAC,CAAC;GAClC,EAAC,CACD,QAAQ,OAAO,GAAG;AAErB,UAAO,MAAM,kBAAkB,KAAK,QAAQ,KAAK,MAAM,YAAY,CAAC;EACrE,SAAQ,GAAG;AACV,SAAM,IAAI,sBACR,CAAC,wBAAwB,EAA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AE,GAAG,EAC/C;EAEH;AAED,SAAO,KAAK,gBAAgB,YAAY;CACzC;CAED,wBAAgC;AAC9B,SAAO,KAAK,sBAAsB,uBAAuB;CAC1D;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xml.cjs","names":["BaseCumulativeTransformOutputParser","fields?: XMLOutputParserFields","prev: unknown | undefined","next: unknown","compare","generations: ChatGeneration[] | Generation[]","text: string","input: ParsedResult","result: XMLResult","s: string","sax","parsedResult: ParsedResult","elementStack: ParsedResult[]","node: any","text: any","attr: any"],"sources":["../../src/output_parsers/xml.ts"],"sourcesContent":["import {\n BaseCumulativeTransformOutputParser,\n BaseCumulativeTransformOutputParserInput,\n} from \"./transform.js\";\nimport { Operation, compare } from \"../utils/json_patch.js\";\nimport { sax } from \"../utils/sax-js/sax.js\";\nimport { ChatGeneration, Generation } from \"../outputs.js\";\n\nexport const XML_FORMAT_INSTRUCTIONS = `The output should be formatted as a XML file.\n1. Output should conform to the tags below. \n2. If tags are not given, make them on your own.\n3. Remember to always open and close all the tags.\n\nAs an example, for the tags [\"foo\", \"bar\", \"baz\"]:\n1. String \"<foo>\\n <bar>\\n <baz></baz>\\n </bar>\\n</foo>\" is a well-formatted instance of the schema. \n2. String \"<foo>\\n <bar>\\n </foo>\" is a badly-formatted instance.\n3. String \"<foo>\\n <tag>\\n </tag>\\n</foo>\" is a badly-formatted instance.\n\nHere are the output tags:\n\\`\\`\\`\n{tags}\n\\`\\`\\``;\n\nexport interface XMLOutputParserFields
|
|
1
|
+
{"version":3,"file":"xml.cjs","names":["BaseCumulativeTransformOutputParser","fields?: XMLOutputParserFields","prev: unknown | undefined","next: unknown","compare","generations: ChatGeneration[] | Generation[]","text: string","input: ParsedResult","result: XMLResult","s: string","sax","parsedResult: ParsedResult","elementStack: ParsedResult[]","node: any","text: any","attr: any"],"sources":["../../src/output_parsers/xml.ts"],"sourcesContent":["import {\n BaseCumulativeTransformOutputParser,\n BaseCumulativeTransformOutputParserInput,\n} from \"./transform.js\";\nimport { Operation, compare } from \"../utils/json_patch.js\";\nimport { sax } from \"../utils/sax-js/sax.js\";\nimport { ChatGeneration, Generation } from \"../outputs.js\";\n\nexport const XML_FORMAT_INSTRUCTIONS = `The output should be formatted as a XML file.\n1. Output should conform to the tags below. \n2. If tags are not given, make them on your own.\n3. Remember to always open and close all the tags.\n\nAs an example, for the tags [\"foo\", \"bar\", \"baz\"]:\n1. String \"<foo>\\n <bar>\\n <baz></baz>\\n </bar>\\n</foo>\" is a well-formatted instance of the schema. \n2. String \"<foo>\\n <bar>\\n </foo>\" is a badly-formatted instance.\n3. String \"<foo>\\n <tag>\\n </tag>\\n</foo>\" is a badly-formatted instance.\n\nHere are the output tags:\n\\`\\`\\`\n{tags}\n\\`\\`\\``;\n\nexport interface XMLOutputParserFields extends BaseCumulativeTransformOutputParserInput {\n /**\n * Optional list of tags that the output should conform to.\n * Only used in formatting of the prompt.\n */\n tags?: string[];\n}\n\nexport type Content = string | undefined | Array<{ [key: string]: Content }>;\n\nexport type XMLResult = {\n [key: string]: Content;\n};\n\nexport class XMLOutputParser extends BaseCumulativeTransformOutputParser<XMLResult> {\n tags?: string[];\n\n constructor(fields?: XMLOutputParserFields) {\n super(fields);\n\n this.tags = fields?.tags;\n }\n\n static lc_name() {\n return \"XMLOutputParser\";\n }\n\n lc_namespace = [\"langchain_core\", \"output_parsers\"];\n\n lc_serializable = true;\n\n protected _diff(\n prev: unknown | undefined,\n next: unknown\n ): Operation[] | undefined {\n if (!next) {\n return undefined;\n }\n if (!prev) {\n return [{ op: \"replace\", path: \"\", value: next }];\n }\n return compare(prev, next);\n }\n\n async parsePartialResult(\n generations: ChatGeneration[] | Generation[]\n ): Promise<XMLResult | undefined> {\n return parseXMLMarkdown(generations[0].text);\n }\n\n async parse(text: string): Promise<XMLResult> {\n return parseXMLMarkdown(text);\n }\n\n getFormatInstructions(): string {\n const withTags = !!(this.tags && this.tags.length > 0);\n return withTags\n ? XML_FORMAT_INSTRUCTIONS.replace(\"{tags}\", this.tags?.join(\", \") ?? \"\")\n : XML_FORMAT_INSTRUCTIONS;\n }\n}\n\nconst strip = (text: string) =>\n text\n .split(\"\\n\")\n .map((line) => line.replace(/^\\s+/, \"\"))\n .join(\"\\n\")\n .trim();\n\ntype ParsedResult = {\n name: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attributes: Record<string, any>;\n children: Array<ParsedResult>;\n text?: string;\n isSelfClosing: boolean;\n};\n\nconst parseParsedResult = (input: ParsedResult): XMLResult => {\n if (Object.keys(input).length === 0) {\n return {};\n }\n const result: XMLResult = {};\n if (input.children.length > 0) {\n result[input.name] = input.children.map(parseParsedResult);\n return result;\n } else {\n result[input.name] = input.text ?? undefined;\n return result;\n }\n};\n\nexport function parseXMLMarkdown(s: string): XMLResult {\n const cleanedString = strip(s);\n const parser = sax.parser(true);\n let parsedResult: ParsedResult = {} as ParsedResult;\n const elementStack: ParsedResult[] = [];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parser.onopentag = (node: any) => {\n const element = {\n name: node.name,\n attributes: node.attributes,\n children: [],\n text: \"\",\n isSelfClosing: node.isSelfClosing,\n };\n\n if (elementStack.length > 0) {\n const parentElement = elementStack[elementStack.length - 1];\n parentElement.children.push(element);\n } else {\n parsedResult = element as ParsedResult;\n }\n\n if (!node.isSelfClosing) {\n elementStack.push(element);\n }\n };\n\n parser.onclosetag = () => {\n if (elementStack.length > 0) {\n const lastElement = elementStack.pop();\n if (elementStack.length === 0 && lastElement) {\n parsedResult = lastElement as ParsedResult;\n }\n }\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parser.ontext = (text: any) => {\n if (elementStack.length > 0) {\n const currentElement = elementStack[elementStack.length - 1];\n currentElement.text += text;\n }\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parser.onattribute = (attr: any) => {\n if (elementStack.length > 0) {\n const currentElement = elementStack[elementStack.length - 1];\n currentElement.attributes[attr.name] = attr.value;\n }\n };\n\n // Try to find XML string within triple backticks.\n const match = /```(xml)?(.*)```/s.exec(cleanedString);\n const xmlString = match ? match[2] : cleanedString;\n parser.write(xmlString).close();\n\n // Remove the XML declaration if present\n if (parsedResult && parsedResult.name === \"?xml\") {\n parsedResult = parsedResult.children[0] as ParsedResult;\n }\n\n return parseParsedResult(parsedResult);\n}\n"],"mappings":";;;;;;AAQA,MAAa,0BAA0B,CAAC;;;;;;;;;;;;;MAalC,CAAC;AAgBP,IAAa,kBAAb,cAAqCA,sDAA+C;CAClF;CAEA,YAAYC,QAAgC;EAC1C,MAAM,OAAO;EAEb,KAAK,OAAO,QAAQ;CACrB;CAED,OAAO,UAAU;AACf,SAAO;CACR;CAED,eAAe,CAAC,kBAAkB,gBAAiB;CAEnD,kBAAkB;CAElB,AAAU,MACRC,MACAC,MACyB;AACzB,MAAI,CAAC,KACH,QAAO;AAET,MAAI,CAAC,KACH,QAAO,CAAC;GAAE,IAAI;GAAW,MAAM;GAAI,OAAO;EAAM,CAAC;AAEnD,SAAOC,uBAAQ,MAAM,KAAK;CAC3B;CAED,MAAM,mBACJC,aACgC;AAChC,SAAO,iBAAiB,YAAY,GAAG,KAAK;CAC7C;CAED,MAAM,MAAMC,MAAkC;AAC5C,SAAO,iBAAiB,KAAK;CAC9B;CAED,wBAAgC;EAC9B,MAAM,WAAW,CAAC,EAAE,KAAK,QAAQ,KAAK,KAAK,SAAS;AACpD,SAAO,WACH,wBAAwB,QAAQ,UAAU,KAAK,MAAM,KAAK,KAAK,IAAI,GAAG,GACtE;CACL;AACF;AAED,MAAM,QAAQ,CAACA,SACb,KACG,MAAM,KAAK,CACX,IAAI,CAAC,SAAS,KAAK,QAAQ,QAAQ,GAAG,CAAC,CACvC,KAAK,KAAK,CACV,MAAM;AAWX,MAAM,oBAAoB,CAACC,UAAmC;AAC5D,KAAI,OAAO,KAAK,MAAM,CAAC,WAAW,EAChC,QAAO,CAAE;CAEX,MAAMC,SAAoB,CAAE;AAC5B,KAAI,MAAM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aAAa;AACvC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xml.js","names":["fields?: XMLOutputParserFields","prev: unknown | undefined","next: unknown","generations: ChatGeneration[] | Generation[]","text: string","input: ParsedResult","result: XMLResult","s: string","parsedResult: ParsedResult","elementStack: ParsedResult[]","node: any","text: any","attr: any"],"sources":["../../src/output_parsers/xml.ts"],"sourcesContent":["import {\n BaseCumulativeTransformOutputParser,\n BaseCumulativeTransformOutputParserInput,\n} from \"./transform.js\";\nimport { Operation, compare } from \"../utils/json_patch.js\";\nimport { sax } from \"../utils/sax-js/sax.js\";\nimport { ChatGeneration, Generation } from \"../outputs.js\";\n\nexport const XML_FORMAT_INSTRUCTIONS = `The output should be formatted as a XML file.\n1. Output should conform to the tags below. \n2. If tags are not given, make them on your own.\n3. Remember to always open and close all the tags.\n\nAs an example, for the tags [\"foo\", \"bar\", \"baz\"]:\n1. String \"<foo>\\n <bar>\\n <baz></baz>\\n </bar>\\n</foo>\" is a well-formatted instance of the schema. \n2. String \"<foo>\\n <bar>\\n </foo>\" is a badly-formatted instance.\n3. String \"<foo>\\n <tag>\\n </tag>\\n</foo>\" is a badly-formatted instance.\n\nHere are the output tags:\n\\`\\`\\`\n{tags}\n\\`\\`\\``;\n\nexport interface XMLOutputParserFields
|
|
1
|
+
{"version":3,"file":"xml.js","names":["fields?: XMLOutputParserFields","prev: unknown | undefined","next: unknown","generations: ChatGeneration[] | Generation[]","text: string","input: ParsedResult","result: XMLResult","s: string","parsedResult: ParsedResult","elementStack: ParsedResult[]","node: any","text: any","attr: any"],"sources":["../../src/output_parsers/xml.ts"],"sourcesContent":["import {\n BaseCumulativeTransformOutputParser,\n BaseCumulativeTransformOutputParserInput,\n} from \"./transform.js\";\nimport { Operation, compare } from \"../utils/json_patch.js\";\nimport { sax } from \"../utils/sax-js/sax.js\";\nimport { ChatGeneration, Generation } from \"../outputs.js\";\n\nexport const XML_FORMAT_INSTRUCTIONS = `The output should be formatted as a XML file.\n1. Output should conform to the tags below. \n2. If tags are not given, make them on your own.\n3. Remember to always open and close all the tags.\n\nAs an example, for the tags [\"foo\", \"bar\", \"baz\"]:\n1. String \"<foo>\\n <bar>\\n <baz></baz>\\n </bar>\\n</foo>\" is a well-formatted instance of the schema. \n2. String \"<foo>\\n <bar>\\n </foo>\" is a badly-formatted instance.\n3. String \"<foo>\\n <tag>\\n </tag>\\n</foo>\" is a badly-formatted instance.\n\nHere are the output tags:\n\\`\\`\\`\n{tags}\n\\`\\`\\``;\n\nexport interface XMLOutputParserFields extends BaseCumulativeTransformOutputParserInput {\n /**\n * Optional list of tags that the output should conform to.\n * Only used in formatting of the prompt.\n */\n tags?: string[];\n}\n\nexport type Content = string | undefined | Array<{ [key: string]: Content }>;\n\nexport type XMLResult = {\n [key: string]: Content;\n};\n\nexport class XMLOutputParser extends BaseCumulativeTransformOutputParser<XMLResult> {\n tags?: string[];\n\n constructor(fields?: XMLOutputParserFields) {\n super(fields);\n\n this.tags = fields?.tags;\n }\n\n static lc_name() {\n return \"XMLOutputParser\";\n }\n\n lc_namespace = [\"langchain_core\", \"output_parsers\"];\n\n lc_serializable = true;\n\n protected _diff(\n prev: unknown | undefined,\n next: unknown\n ): Operation[] | undefined {\n if (!next) {\n return undefined;\n }\n if (!prev) {\n return [{ op: \"replace\", path: \"\", value: next }];\n }\n return compare(prev, next);\n }\n\n async parsePartialResult(\n generations: ChatGeneration[] | Generation[]\n ): Promise<XMLResult | undefined> {\n return parseXMLMarkdown(generations[0].text);\n }\n\n async parse(text: string): Promise<XMLResult> {\n return parseXMLMarkdown(text);\n }\n\n getFormatInstructions(): string {\n const withTags = !!(this.tags && this.tags.length > 0);\n return withTags\n ? XML_FORMAT_INSTRUCTIONS.replace(\"{tags}\", this.tags?.join(\", \") ?? \"\")\n : XML_FORMAT_INSTRUCTIONS;\n }\n}\n\nconst strip = (text: string) =>\n text\n .split(\"\\n\")\n .map((line) => line.replace(/^\\s+/, \"\"))\n .join(\"\\n\")\n .trim();\n\ntype ParsedResult = {\n name: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attributes: Record<string, any>;\n children: Array<ParsedResult>;\n text?: string;\n isSelfClosing: boolean;\n};\n\nconst parseParsedResult = (input: ParsedResult): XMLResult => {\n if (Object.keys(input).length === 0) {\n return {};\n }\n const result: XMLResult = {};\n if (input.children.length > 0) {\n result[input.name] = input.children.map(parseParsedResult);\n return result;\n } else {\n result[input.name] = input.text ?? undefined;\n return result;\n }\n};\n\nexport function parseXMLMarkdown(s: string): XMLResult {\n const cleanedString = strip(s);\n const parser = sax.parser(true);\n let parsedResult: ParsedResult = {} as ParsedResult;\n const elementStack: ParsedResult[] = [];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parser.onopentag = (node: any) => {\n const element = {\n name: node.name,\n attributes: node.attributes,\n children: [],\n text: \"\",\n isSelfClosing: node.isSelfClosing,\n };\n\n if (elementStack.length > 0) {\n const parentElement = elementStack[elementStack.length - 1];\n parentElement.children.push(element);\n } else {\n parsedResult = element as ParsedResult;\n }\n\n if (!node.isSelfClosing) {\n elementStack.push(element);\n }\n };\n\n parser.onclosetag = () => {\n if (elementStack.length > 0) {\n const lastElement = elementStack.pop();\n if (elementStack.length === 0 && lastElement) {\n parsedResult = lastElement as ParsedResult;\n }\n }\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parser.ontext = (text: any) => {\n if (elementStack.length > 0) {\n const currentElement = elementStack[elementStack.length - 1];\n currentElement.text += text;\n }\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parser.onattribute = (attr: any) => {\n if (elementStack.length > 0) {\n const currentElement = elementStack[elementStack.length - 1];\n currentElement.attributes[attr.name] = attr.value;\n }\n };\n\n // Try to find XML string within triple backticks.\n const match = /```(xml)?(.*)```/s.exec(cleanedString);\n const xmlString = match ? match[2] : cleanedString;\n parser.write(xmlString).close();\n\n // Remove the XML declaration if present\n if (parsedResult && parsedResult.name === \"?xml\") {\n parsedResult = parsedRes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BC,GAAsB;CACrD,MAAM,gBAAgB,MAAM,EAAE;CAC9B,MAAM,SAAS,IAAI,OAAO,KAAK;CAC/B,IAAIC,eAA6B,CAAE;CACnC,MAAMC,eAA+B,CAAE;CAGvC,OAAO,YAAY,CAACC,SAAc;EAChC,MAAM,UAAU;GACd,MAAM,KAAK;GACX,YAAY,KAAK;GACjB,UAAU,CAAE;GACZ,MAAM;GACN,eAAe,KAAK;EACrB;AAED,MAAI,aAAa,SAAS,GAAG;GAC3B,MAAM,gBAAgB,aAAa,aAAa,SAAS;GACzD,cAAc,SAAS,KAAK,QAAQ;EACrC,OACC,eAAe;AAGjB,MAAI,CAAC,KAAK,eACR,aAAa,KAAK,QAAQ;CAE7B;CAED,OAAO,aAAa,MAAM;AACxB,MAAI,aAAa,SAAS,GAAG;GAC3B,MAAM,cAAc,aAAa,KAAK;AACtC,OAAI,aAAa,WAAW,KAAK,aAC/B,eAAe;EAElB;CACF;CAGD,OAAO,SAAS,CAACC,SAAc;AAC7B,MAAI,aAAa,SAAS,GAAG;GAC3B,MAAM,iBAAiB,aAAa,aAAa,SAAS;GAC1D,eAAe,QAAQ;EACxB;CACF;CAGD,OAAO,cAAc,CAACC,SAAc;AAClC,MAAI,aAAa,SAAS,GAAG;GAC3B,MAAM,iBAAiB,aAAa,aAAa,SAAS;GAC1D,eAAe,WAAW,KAAK,QAAQ,KAAK;EAC7C;CACF;CAGD,MAAM,QAAQ,oBAAoB,KAAK,cAAc;CACrD,MAAM,YAAY,QAAQ,MAAM,KAAK;CACrC,OAAO,MAAM,UAAU,CAAC,OAAO;AAG/B,KAAI,gBAAgB,aAAa,SAAS,QACxC,eAAe,aAAa,SAAS;AAGvC,QAAO,kBAAkB,aAAa;AACvC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.cjs","names":["Runnable","input: BasePromptTemplateInput","userVariables: TypedPromptInputValues<RunInput>","partialValues: Record<string, string>","input: RunInput","options?: BaseCallbackConfig","input"],"sources":["../../src/prompts/base.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport type {\n InputValues,\n PartialValues,\n StringWithAutocomplete,\n} from \"../utils/types/index.js\";\nimport { type BasePromptValueInterface } from \"../prompt_values.js\";\nimport { BaseOutputParser } from \"../output_parsers/index.js\";\nimport type { SerializedFields } from \"../load/map_keys.js\";\nimport { Runnable } from \"../runnables/base.js\";\nimport { BaseCallbackConfig } from \"../callbacks/manager.js\";\n\nexport type TypedPromptInputValues<RunInput> = InputValues<\n StringWithAutocomplete<Extract<keyof RunInput, string>>\n>;\n\nexport type Example = Record<string, string>;\n\n/**\n * Input common to all prompt templates.\n */\nexport interface BasePromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n InputVariables extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n> {\n /**\n * A list of variable names the prompt template expects\n */\n inputVariables: Array<Extract<keyof InputVariables, string>>;\n\n /**\n * How to parse the output of calling an LLM on this formatted prompt\n */\n outputParser?: BaseOutputParser;\n\n /** Partial variables */\n partialVariables?: PartialValues<PartialVariableName>;\n}\n\n/**\n * Base class for prompt templates. Exposes a format method that returns a\n * string prompt given a set of input values.\n */\nexport abstract class BasePromptTemplate<\n
|
|
1
|
+
{"version":3,"file":"base.cjs","names":["Runnable","input: BasePromptTemplateInput","userVariables: TypedPromptInputValues<RunInput>","partialValues: Record<string, string>","input: RunInput","options?: BaseCallbackConfig","input"],"sources":["../../src/prompts/base.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport type {\n InputValues,\n PartialValues,\n StringWithAutocomplete,\n} from \"../utils/types/index.js\";\nimport { type BasePromptValueInterface } from \"../prompt_values.js\";\nimport { BaseOutputParser } from \"../output_parsers/index.js\";\nimport type { SerializedFields } from \"../load/map_keys.js\";\nimport { Runnable } from \"../runnables/base.js\";\nimport { BaseCallbackConfig } from \"../callbacks/manager.js\";\n\nexport type TypedPromptInputValues<RunInput> = InputValues<\n StringWithAutocomplete<Extract<keyof RunInput, string>>\n>;\n\nexport type Example = Record<string, string>;\n\n/**\n * Input common to all prompt templates.\n */\nexport interface BasePromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n InputVariables extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n> {\n /**\n * A list of variable names the prompt template expects\n */\n inputVariables: Array<Extract<keyof InputVariables, string>>;\n\n /**\n * How to parse the output of calling an LLM on this formatted prompt\n */\n outputParser?: BaseOutputParser;\n\n /** Partial variables */\n partialVariables?: PartialValues<PartialVariableName>;\n}\n\n/**\n * Base class for prompt templates. Exposes a format method that returns a\n * string prompt given a set of input values.\n */\nexport abstract class BasePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n RunOutput extends BasePromptValueInterface = BasePromptValueInterface,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n>\n extends Runnable<RunInput, RunOutput>\n implements BasePromptTemplateInput\n{\n declare PromptValueReturnType: RunOutput;\n\n lc_serializable = true;\n\n lc_namespace = [\"langchain_core\", \"prompts\", this._getPromptType()];\n\n get lc_attributes(): SerializedFields | undefined {\n return {\n partialVariables: undefined, // python doesn't support this yet\n };\n }\n\n inputVariables: Array<Extract<keyof RunInput, string>>;\n\n outputParser?: BaseOutputParser;\n\n partialVariables: PartialValues<PartialVariableName>;\n\n /**\n * Metadata to be used for tracing.\n */\n metadata?: Record<string, unknown>;\n\n /** Tags to be used for tracing. */\n tags?: string[];\n\n constructor(input: BasePromptTemplateInput) {\n super(input);\n const { inputVariables } = input;\n if (inputVariables.includes(\"stop\")) {\n throw new Error(\n \"Cannot have an input variable named 'stop', as it is used internally, please rename.\"\n );\n }\n Object.assign(this, input);\n }\n\n abstract partial(\n values: PartialValues\n ): Promise<BasePromptTemplate<RunInput, RunOutput, PartialVariableName>>;\n\n /**\n * Merges partial variables and user variables.\n * @param userVariables The user variables to merge with the partial variables.\n * @returns A Promise that resolves to an object containing the merged variables.\n */\n async mergePartialAndUserVariables(\n userVariables: TypedPromptInputValues<RunInput>\n ): Promise<\n InputValues<Extract<keyof RunInput, string> | PartialVariableName>\n > {\n const partialVariables = this.partialVariables ?? {};\n const partialValues: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(partialVariables)) {\n if (typeof value === \"string\") {\n partialValues[key] = value;\n } else {\n partialValues[key] = await (value as () => Promise<string>)();\n }\n }\n\n const allKwargs = {\n ...(partialValues as Record<PartialVariableName, string>),\n ...userVariables,\n };\n return allKwargs;\n }\n\n /**\n * Invokes the prompt template with the given input and options.\n * @param input The input to invoke the prompt template with.\n * @param options Optional configuration for the callback.\n * @returns A Promise that resolves to the output of the prompt template.\n */\n async invoke(\n input: RunInput,\n options?: BaseCallbackConfig\n ): Promise<RunOutput> {\n const metadata = {\n ...this.metadata,\n ...options?.metadata,\n };\n const tags = [...(this.tags ?? []), ...(options?.tags ?? [])];\n return this._callWithConfig(\n (input: RunInput) => this.formatPromptValue(input),\n input,\n { ...options, tags, metadata, runType: \"prompt\" }\n );\n }\n\n /**\n * Format the prompt given the input values.\n *\n * @param values - A dictionary of arguments to be passed to the prompt template.\n * @returns A formatted prompt string.\n *\n * @example\n * ```ts\n * prompt.format({ foo: \"bar\" });\n * ```\n */\n abstract format(values: TypedPromptInputValues<RunInput>): Promise<string>;\n\n /**\n * Format the prompt given the input values and return a formatted prompt value.\n * @param values\n * @returns A formatted PromptValue.\n */\n abstract formatPromptValue(\n values: TypedPromptInputValues<RunInput>\n ): Promise<RunOutput>;\n\n /**\n * Return the string type key uniquely identifying this class of prompt template.\n */\n abstract _getPromptType(): string;\n}\n"],"mappings":";;;;;;;AA+CA,IAAsB,qBAAtB,cAOUA,sBAEV;CAGE,kBAAkB;CAElB,eAAe;EAAC;EAAkB;EAAW,KAAK,gBAAgB;CAAC;CAEnE,IAAI,gBAA8C;AAChD,SAAO,EACL,kBAAkB,OACnB;CACF;CAED;CAEA;CAEA;;;;CAKA;;CAGA;CAEA,YAAYC,OAAgC;EAC1C,MAAM,MAAM;EACZ,MAAM,EAAE,gBAAgB,GAAG;AAC3B,MAAI,eAAe,SAAS,OAAO,CACjC,OAAM,IAAI,MACR;EAGJ,OAAO,OAAO,MAAM,MAAM;CAC3B;;;;;;CAWD,MAAM,6BACJC,eAGA;EACA,MAAM,mBAAmB,KAAK,oBAAoB,CAAE;EACpD,MAAMC,gBAAwC,CAAE;AAEhD,OAAK,MAAM,CAAC,KAAK,MAAM,IAAI,OAAO,QAAQ,iBAAiB,CACzD,KAAI,OAAO,UAAU,UACnB,cAAc,OAAO;OAErB,cAAc,OAAO,MAAO,OAAiC;EAIjE,MAAM,YAAY;GAChB,GAAI;GACJ,GAAG;EACJ;AACD,SAAO;CACR;;;;;;;CAQD,MAAM,OACJC,OACAC,SACoB;EACpB,MAAM,WAAW;GACf,GAAG,KAAK;GACR,GAAG,SAAS;EACb;EACD,MAAM,OAAO,CAAC,GAAI,KAAK,QAAQ,CAAE,GAAG,GAAI,SAAS,QAAQ,CAAE,CAAE;AAC7D,SAAO,KAAK,gBACV,CAACD,YAAoB,KAAK,kBAAkBE,QAAM,EAClD,OACA;GAAE,GAAG;GAAS;GAAM;GAAU,SAAS;EAAU,EAClD;CACF;AA4BF"}
|
package/dist/prompts/base.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":["input: BasePromptTemplateInput","userVariables: TypedPromptInputValues<RunInput>","partialValues: Record<string, string>","input: RunInput","options?: BaseCallbackConfig","input"],"sources":["../../src/prompts/base.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport type {\n InputValues,\n PartialValues,\n StringWithAutocomplete,\n} from \"../utils/types/index.js\";\nimport { type BasePromptValueInterface } from \"../prompt_values.js\";\nimport { BaseOutputParser } from \"../output_parsers/index.js\";\nimport type { SerializedFields } from \"../load/map_keys.js\";\nimport { Runnable } from \"../runnables/base.js\";\nimport { BaseCallbackConfig } from \"../callbacks/manager.js\";\n\nexport type TypedPromptInputValues<RunInput> = InputValues<\n StringWithAutocomplete<Extract<keyof RunInput, string>>\n>;\n\nexport type Example = Record<string, string>;\n\n/**\n * Input common to all prompt templates.\n */\nexport interface BasePromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n InputVariables extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n> {\n /**\n * A list of variable names the prompt template expects\n */\n inputVariables: Array<Extract<keyof InputVariables, string>>;\n\n /**\n * How to parse the output of calling an LLM on this formatted prompt\n */\n outputParser?: BaseOutputParser;\n\n /** Partial variables */\n partialVariables?: PartialValues<PartialVariableName>;\n}\n\n/**\n * Base class for prompt templates. Exposes a format method that returns a\n * string prompt given a set of input values.\n */\nexport abstract class BasePromptTemplate<\n
|
|
1
|
+
{"version":3,"file":"base.js","names":["input: BasePromptTemplateInput","userVariables: TypedPromptInputValues<RunInput>","partialValues: Record<string, string>","input: RunInput","options?: BaseCallbackConfig","input"],"sources":["../../src/prompts/base.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport type {\n InputValues,\n PartialValues,\n StringWithAutocomplete,\n} from \"../utils/types/index.js\";\nimport { type BasePromptValueInterface } from \"../prompt_values.js\";\nimport { BaseOutputParser } from \"../output_parsers/index.js\";\nimport type { SerializedFields } from \"../load/map_keys.js\";\nimport { Runnable } from \"../runnables/base.js\";\nimport { BaseCallbackConfig } from \"../callbacks/manager.js\";\n\nexport type TypedPromptInputValues<RunInput> = InputValues<\n StringWithAutocomplete<Extract<keyof RunInput, string>>\n>;\n\nexport type Example = Record<string, string>;\n\n/**\n * Input common to all prompt templates.\n */\nexport interface BasePromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n InputVariables extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n> {\n /**\n * A list of variable names the prompt template expects\n */\n inputVariables: Array<Extract<keyof InputVariables, string>>;\n\n /**\n * How to parse the output of calling an LLM on this formatted prompt\n */\n outputParser?: BaseOutputParser;\n\n /** Partial variables */\n partialVariables?: PartialValues<PartialVariableName>;\n}\n\n/**\n * Base class for prompt templates. Exposes a format method that returns a\n * string prompt given a set of input values.\n */\nexport abstract class BasePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n RunOutput extends BasePromptValueInterface = BasePromptValueInterface,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n>\n extends Runnable<RunInput, RunOutput>\n implements BasePromptTemplateInput\n{\n declare PromptValueReturnType: RunOutput;\n\n lc_serializable = true;\n\n lc_namespace = [\"langchain_core\", \"prompts\", this._getPromptType()];\n\n get lc_attributes(): SerializedFields | undefined {\n return {\n partialVariables: undefined, // python doesn't support this yet\n };\n }\n\n inputVariables: Array<Extract<keyof RunInput, string>>;\n\n outputParser?: BaseOutputParser;\n\n partialVariables: PartialValues<PartialVariableName>;\n\n /**\n * Metadata to be used for tracing.\n */\n metadata?: Record<string, unknown>;\n\n /** Tags to be used for tracing. */\n tags?: string[];\n\n constructor(input: BasePromptTemplateInput) {\n super(input);\n const { inputVariables } = input;\n if (inputVariables.includes(\"stop\")) {\n throw new Error(\n \"Cannot have an input variable named 'stop', as it is used internally, please rename.\"\n );\n }\n Object.assign(this, input);\n }\n\n abstract partial(\n values: PartialValues\n ): Promise<BasePromptTemplate<RunInput, RunOutput, PartialVariableName>>;\n\n /**\n * Merges partial variables and user variables.\n * @param userVariables The user variables to merge with the partial variables.\n * @returns A Promise that resolves to an object containing the merged variables.\n */\n async mergePartialAndUserVariables(\n userVariables: TypedPromptInputValues<RunInput>\n ): Promise<\n InputValues<Extract<keyof RunInput, string> | PartialVariableName>\n > {\n const partialVariables = this.partialVariables ?? {};\n const partialValues: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(partialVariables)) {\n if (typeof value === \"string\") {\n partialValues[key] = value;\n } else {\n partialValues[key] = await (value as () => Promise<string>)();\n }\n }\n\n const allKwargs = {\n ...(partialValues as Record<PartialVariableName, string>),\n ...userVariables,\n };\n return allKwargs;\n }\n\n /**\n * Invokes the prompt template with the given input and options.\n * @param input The input to invoke the prompt template with.\n * @param options Optional configuration for the callback.\n * @returns A Promise that resolves to the output of the prompt template.\n */\n async invoke(\n input: RunInput,\n options?: BaseCallbackConfig\n ): Promise<RunOutput> {\n const metadata = {\n ...this.metadata,\n ...options?.metadata,\n };\n const tags = [...(this.tags ?? []), ...(options?.tags ?? [])];\n return this._callWithConfig(\n (input: RunInput) => this.formatPromptValue(input),\n input,\n { ...options, tags, metadata, runType: \"prompt\" }\n );\n }\n\n /**\n * Format the prompt given the input values.\n *\n * @param values - A dictionary of arguments to be passed to the prompt template.\n * @returns A formatted prompt string.\n *\n * @example\n * ```ts\n * prompt.format({ foo: \"bar\" });\n * ```\n */\n abstract format(values: TypedPromptInputValues<RunInput>): Promise<string>;\n\n /**\n * Format the prompt given the input values and return a formatted prompt value.\n * @param values\n * @returns A formatted PromptValue.\n */\n abstract formatPromptValue(\n values: TypedPromptInputValues<RunInput>\n ): Promise<RunOutput>;\n\n /**\n * Return the string type key uniquely identifying this class of prompt template.\n */\n abstract _getPromptType(): string;\n}\n"],"mappings":";;;;;;;AA+CA,IAAsB,qBAAtB,cAOU,SAEV;CAGE,kBAAkB;CAElB,eAAe;EAAC;EAAkB;EAAW,KAAK,gBAAgB;CAAC;CAEnE,IAAI,gBAA8C;AAChD,SAAO,EACL,kBAAkB,OACnB;CACF;CAED;CAEA;CAEA;;;;CAKA;;CAGA;CAEA,YAAYA,OAAgC;EAC1C,MAAM,MAAM;EACZ,MAAM,EAAE,gBAAgB,GAAG;AAC3B,MAAI,eAAe,SAAS,OAAO,CACjC,OAAM,IAAI,MACR;EAGJ,OAAO,OAAO,MAAM,MAAM;CAC3B;;;;;;CAWD,MAAM,6BACJC,eAGA;EACA,MAAM,mBAAmB,KAAK,oBAAoB,CAAE;EACpD,MAAMC,gBAAwC,CAAE;AAEhD,OAAK,MAAM,CAAC,KAAK,MAAM,IAAI,OAAO,QAAQ,iBAAiB,CACzD,KAAI,OAAO,UAAU,UACnB,cAAc,OAAO;OAErB,cAAc,OAAO,MAAO,OAAiC;EAIjE,MAAM,YAAY;GAChB,GAAI;GACJ,GAAG;EACJ;AACD,SAAO;CACR;;;;;;;CAQD,MAAM,OACJC,OACAC,SACoB;EACpB,MAAM,WAAW;GACf,GAAG,KAAK;GACR,GAAG,SAAS;EACb;EACD,MAAM,OAAO,CAAC,GAAI,KAAK,QAAQ,CAAE,GAAG,GAAI,SAAS,QAAQ,CAAE,CAAE;AAC7D,SAAO,KAAK,gBACV,CAACD,YAAoB,KAAK,kBAAkBE,QAAM,EAClD,OACA;GAAE,GAAG;GAAS;GAAM;GAAU,SAAS;EAAU,EAClD;CACF;AA4BF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.cjs","names":["Runnable","input: RunInput","options?: BaseCallbackConfig","input","fields:\n | Extract<keyof RunInput, string>\n | MessagesPlaceholderFields<Extract<keyof RunInput, string>>","values: TypedPromptInputValues<RunInput>","coerceMessageLikeToMessage","e: any","fields:\n | MessageStringPromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n | BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>,\n string\n >","BasePromptTemplate","input: BasePromptTemplateInput<RunInput, PartialVariableName>","ChatPromptValue","fields:\n | ChatMessagePromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n | BaseStringPromptTemplate<InputValues<Extract<keyof RunInput, string>>>","role?: string","values: RunInput","ChatMessage","template: T","role: string","options?: { templateFormat?: TemplateFormat }","PromptTemplate","param: unknown","fields: any","additionalOptions?: _StringImageMessagePromptTemplateOptions","inputVariables: Extract<keyof RunInput, string>[]","content: MessageContent","name: string","template:\n | string\n | Array<\n | string\n | _TextTemplateParam\n | _ImageTemplateParam\n | Record<string, unknown>\n >","prompt: Array<\n | PromptTemplate<InputValues>\n | ImagePromptTemplate<InputValues>\n | DictPromptTemplate\n >","imgTemplateObject: ImagePromptTemplate<InputValues>","inputVariables: string[]","parsedTemplate: ParsedTemplateNode[]","parseMustache","parseFString","item","ImagePromptTemplate","DictPromptTemplate","input: TypedPromptInputValues<RunInput>","BaseStringPromptTemplate","inputs: Record<string, any>","additionalContentFields: ContentBlock | undefined","HumanMessage","AIMessage","SystemMessage","baseMessagePromptTemplateLike: BaseMessagePromptTemplateLike","messagePromptTemplateLike: BaseMessagePromptTemplateLike","extra?: Extra","isBaseMessage","templateData:\n | string\n | (\n | string\n | _TextTemplateParam\n | _ImageTemplateParam\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>\n )[]","x: BaseMessagePromptTemplate | BaseMessage","input: ChatPromptTemplateInput<RunInput, PartialVariableName>","BaseMessage","message: BaseMessage","inputValues: InputValues<\n PartialVariableName | Extract<keyof RunInput, string>\n >","resultMessages: BaseMessage[]","inputValues: InputValues","addLangChainErrorFields","values: PartialValues<NewPartialVariableName>","options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >","promptMessages: (\n | ChatPromptTemplate<InputValues, string>\n | BaseMessagePromptTemplateLike\n )[]","extra?: Omit<\n Extra,\n \"inputVariables\" | \"promptMessages\" | \"partialVariables\"\n >","acc: Array<BaseMessagePromptTemplate | BaseMessage>"],"sources":["../../src/prompts/chat.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport type { BaseCallbackConfig } from \"../callbacks/manager.js\";\nimport {\n AIMessage,\n HumanMessage,\n SystemMessage,\n BaseMessage,\n ChatMessage,\n type BaseMessageLike,\n coerceMessageLikeToMessage,\n isBaseMessage,\n MessageContent,\n ContentBlock,\n} from \"../messages/index.js\";\nimport {\n type ChatPromptValueInterface,\n ChatPromptValue,\n} from \"../prompt_values.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport { Runnable } from \"../runnables/base.js\";\nimport { BaseStringPromptTemplate } from \"./string.js\";\nimport {\n BasePromptTemplate,\n type BasePromptTemplateInput,\n type TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n PromptTemplate,\n type ParamsFromFString,\n PromptTemplateInput,\n ExtractedFStringParams,\n} from \"./prompt.js\";\nimport { ImagePromptTemplate } from \"./image.js\";\nimport {\n ParsedTemplateNode,\n TemplateFormat,\n parseFString,\n parseMustache,\n} from \"./template.js\";\nimport { addLangChainErrorFields } from \"../errors/index.js\";\nimport { DictPromptTemplate } from \"./dict.js\";\n\n/**\n * Abstract class that serves as a base for creating message prompt\n * templates. It defines how to format messages for different roles in a\n * conversation.\n */\nexport abstract class BaseMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n RunOutput extends BaseMessage[] = BaseMessage[],\n> extends Runnable<RunInput, RunOutput> {\n lc_namespace = [\"langchain_core\", \"prompts\", \"chat\"];\n\n lc_serializable = true;\n\n abstract inputVariables: Array<Extract<keyof RunInput, string>>;\n\n /**\n * Method that takes an object of TypedPromptInputValues and returns a\n * promise that resolves to an array of BaseMessage instances.\n * @param values Object of TypedPromptInputValues\n * @returns Formatted array of BaseMessages\n */\n abstract formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<RunOutput>;\n\n /**\n * Calls the formatMessages method with the provided input and options.\n * @param input Input for the formatMessages method\n * @param options Optional BaseCallbackConfig\n * @returns Formatted output messages\n */\n async invoke(\n input: RunInput,\n options?: BaseCallbackConfig\n ): Promise<RunOutput> {\n return this._callWithConfig(\n (input: RunInput) => this.formatMessages(input),\n input,\n { ...options, runType: \"prompt\" }\n );\n }\n}\n\n/**\n * Interface for the fields of a MessagePlaceholder.\n */\nexport interface MessagesPlaceholderFields<T extends string> {\n variableName: T;\n optional?: boolean;\n}\n\n/**\n * Class that represents a placeholder for messages in a chat prompt. It\n * extends the BaseMessagePromptTemplate.\n */\nexport class MessagesPlaceholder<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n >\n extends BaseMessagePromptTemplate<RunInput>\n implements MessagesPlaceholderFields<Extract<keyof RunInput, string>>\n{\n static lc_name() {\n return \"MessagesPlaceholder\";\n }\n\n variableName: Extract<keyof RunInput, string>;\n\n optional: boolean;\n\n constructor(variableName: Extract<keyof RunInput, string>);\n\n constructor(\n fields: MessagesPlaceholderFields<Extract<keyof RunInput, string>>\n );\n\n constructor(\n fields:\n | Extract<keyof RunInput, string>\n | MessagesPlaceholderFields<Extract<keyof RunInput, string>>\n ) {\n if (typeof fields === \"string\") {\n // eslint-disable-next-line no-param-reassign\n fields = { variableName: fields };\n }\n super(fields);\n this.variableName = fields.variableName;\n this.optional = fields.optional ?? false;\n }\n\n get inputVariables() {\n return [this.variableName];\n }\n\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n const input = values[this.variableName];\n if (this.optional && !input) {\n return [];\n } else if (!input) {\n const error = new Error(\n `Field \"${this.variableName}\" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`\n );\n error.name = \"InputFormatError\";\n throw error;\n }\n\n let formattedMessages;\n try {\n if (Array.isArray(input)) {\n formattedMessages = input.map(coerceMessageLikeToMessage);\n } else {\n formattedMessages = [coerceMessageLikeToMessage(input)];\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n const readableInput =\n typeof input === \"string\" ? input : JSON.stringify(input, null, 2);\n const error = new Error(\n [\n `Field \"${this.variableName}\" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,\n `Received value: ${readableInput}`,\n `Additional message: ${e.message}`,\n ].join(\"\\n\\n\")\n );\n error.name = \"InputFormatError\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).lc_error_code = e.lc_error_code;\n throw error;\n }\n\n return formattedMessages;\n }\n}\n\n/**\n * Interface for the fields of a MessageStringPromptTemplate.\n */\nexport interface MessageStringPromptTemplateFields<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends InputValues = any,\n> {\n prompt: BaseStringPromptTemplate<T, string>;\n}\n\n/**\n * Abstract class that serves as a base for creating message string prompt\n * templates. It extends the BaseMessagePromptTemplate.\n */\nexport abstract class BaseMessageStringPromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n> extends BaseMessagePromptTemplate<RunInput> {\n prompt: BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>,\n string\n >;\n\n constructor(\n prompt: BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>\n >\n );\n\n constructor(\n fields: MessageStringPromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n );\n\n constructor(\n fields:\n | MessageStringPromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n | BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>,\n string\n >\n ) {\n if (!(\"prompt\" in fields)) {\n // eslint-disable-next-line no-param-reassign\n fields = { prompt: fields };\n }\n super(fields);\n this.prompt = fields.prompt;\n }\n\n get inputVariables() {\n return this.prompt.inputVariables;\n }\n\n abstract format(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage>;\n\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n return [await this.format(values)];\n }\n}\n\n/**\n * Abstract class that serves as a base for creating chat prompt\n * templates. It extends the BasePromptTemplate.\n */\nexport abstract class BaseChatPromptTemplate<\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 BasePromptTemplate<\n RunInput,\n ChatPromptValueInterface,\n PartialVariableName\n> {\n constructor(input: BasePromptTemplateInput<RunInput, PartialVariableName>) {\n super(input);\n }\n\n abstract formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]>;\n\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n return (await this.formatPromptValue(values)).toString();\n }\n\n async formatPromptValue(\n values: TypedPromptInputValues<RunInput>\n ): Promise<ChatPromptValueInterface> {\n const resultMessages = await this.formatMessages(values);\n return new ChatPromptValue(resultMessages);\n }\n}\n\n/**\n * Interface for the fields of a ChatMessagePromptTemplate.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface ChatMessagePromptTemplateFields<T extends InputValues = any>\n extends MessageStringPromptTemplateFields<T> {\n role: string;\n}\n\n/**\n * Class that represents a chat message prompt template. It extends the\n * BaseMessageStringPromptTemplate.\n */\nexport class ChatMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n> extends BaseMessageStringPromptTemplate<RunInput> {\n static lc_name() {\n return \"ChatMessagePromptTemplate\";\n }\n\n role: string;\n\n constructor(\n prompt: BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>\n >,\n role: string\n );\n\n constructor(\n fields: ChatMessagePromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n );\n\n constructor(\n fields:\n | ChatMessagePromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n | BaseStringPromptTemplate<InputValues<Extract<keyof RunInput, string>>>,\n role?: string\n ) {\n if (!(\"prompt\" in fields)) {\n // eslint-disable-next-line no-param-reassign\n fields = { prompt: fields, role: role! };\n }\n super(fields);\n this.role = fields.role;\n }\n\n async format(values: RunInput): Promise<BaseMessage> {\n return new ChatMessage(await this.prompt.format(values), this.role);\n }\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(template: T, role: string, options?: { templateFormat?: TemplateFormat }) {\n return new this(\n PromptTemplate.fromTemplate<RunInput, T>(template, {\n templateFormat: options?.templateFormat,\n }),\n role\n );\n }\n}\n\ninterface _TextTemplateParam {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n text?: string | Record<string, any>;\n}\n\nfunction isTextTemplateParam(param: unknown): param is _TextTemplateParam {\n if (param === null || typeof param !== \"object\" || Array.isArray(param)) {\n return false;\n }\n return (\n Object.keys(param).length === 1 &&\n \"text\" in param &&\n typeof param.text === \"string\"\n );\n}\n\ninterface _ImageTemplateParam {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n image_url?: string | Record<string, any>;\n}\n\nfunction isImageTemplateParam(param: unknown): param is _ImageTemplateParam {\n if (param === null || typeof param !== \"object\" || Array.isArray(param)) {\n return false;\n }\n return (\n \"image_url\" in param &&\n (typeof param.image_url === \"string\" ||\n (typeof param.image_url === \"object\" &&\n param.image_url !== null &&\n \"url\" in param.image_url &&\n typeof param.image_url.url === \"string\"))\n );\n}\n\ntype MessageClass =\n | typeof HumanMessage\n | typeof AIMessage\n | typeof SystemMessage;\n\ntype ChatMessageClass = typeof ChatMessage;\n\ninterface _StringImageMessagePromptTemplateOptions<\n Format extends TemplateFormat = TemplateFormat,\n> extends Record<string, unknown> {\n templateFormat?: Format;\n}\n\nclass _StringImageMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n RunOutput extends BaseMessage[] = BaseMessage[],\n> extends BaseMessagePromptTemplate<RunInput, RunOutput> {\n lc_namespace = [\"langchain_core\", \"prompts\", \"chat\"];\n\n lc_serializable = true;\n\n inputVariables: Array<Extract<keyof RunInput, string>> = [];\n\n additionalOptions: _StringImageMessagePromptTemplateOptions = {};\n\n prompt:\n | BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>,\n string\n >\n | Array<\n | BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>,\n string\n >\n | ImagePromptTemplate<\n InputValues<Extract<keyof RunInput, string>>,\n string\n >\n | MessageStringPromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n | DictPromptTemplate<InputValues<Extract<keyof RunInput, string>>>\n >;\n\n protected messageClass?: MessageClass;\n\n static _messageClass(): MessageClass {\n throw new Error(\n \"Can not invoke _messageClass from inside _StringImageMessagePromptTemplate\"\n );\n }\n\n // ChatMessage contains role field, others don't.\n // Because of this, we have a separate class property for ChatMessage.\n protected chatMessageClass?: ChatMessageClass;\n\n constructor(\n /** @TODO When we come up with a better way to type prompt templates, fix this */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fields: any,\n additionalOptions?: _StringImageMessagePromptTemplateOptions\n ) {\n if (!(\"prompt\" in fields)) {\n // eslint-disable-next-line no-param-reassign\n fields = { prompt: fields };\n }\n super(fields);\n this.prompt = fields.prompt;\n if (Array.isArray(this.prompt)) {\n let inputVariables: Extract<keyof RunInput, string>[] = [];\n this.prompt.forEach((prompt) => {\n if (\"inputVariables\" in prompt) {\n inputVariables = inputVariables.concat(prompt.inputVariables);\n }\n });\n this.inputVariables = inputVariables;\n } else {\n this.inputVariables = this.prompt.inputVariables;\n }\n this.additionalOptions = additionalOptions ?? this.additionalOptions;\n }\n\n createMessage(content: MessageContent) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const constructor = this.constructor as any;\n if (constructor._messageClass()) {\n const MsgClass = constructor._messageClass();\n return new MsgClass({ content });\n } else if (constructor.chatMessageClass) {\n const MsgClass = constructor.chatMessageClass();\n // Assuming ChatMessage constructor also takes a content argument\n return new MsgClass({\n content,\n role: this.getRoleFromMessageClass(MsgClass.lc_name()),\n });\n } else {\n throw new Error(\"No message class defined\");\n }\n }\n\n getRoleFromMessageClass(name: string) {\n switch (name) {\n case \"HumanMessage\":\n return \"human\";\n case \"AIMessage\":\n return \"ai\";\n case \"SystemMessage\":\n return \"system\";\n case \"ChatMessage\":\n return \"chat\";\n default:\n throw new Error(\"Invalid message class name\");\n }\n }\n\n static fromTemplate(\n template:\n | string\n | Array<\n | string\n | _TextTemplateParam\n | _ImageTemplateParam\n | Record<string, unknown>\n >,\n additionalOptions?: _StringImageMessagePromptTemplateOptions\n ) {\n if (typeof template === \"string\") {\n return new this(PromptTemplate.fromTemplate(template, additionalOptions));\n }\n const prompt: Array<\n | PromptTemplate<InputValues>\n | ImagePromptTemplate<InputValues>\n | DictPromptTemplate\n > = [];\n for (const item of template) {\n // handle string cases\n if (typeof item === \"string\") {\n prompt.push(PromptTemplate.fromTemplate(item, additionalOptions));\n } else if (item === null) {\n // pass\n } else if (isTextTemplateParam(item)) {\n let text = \"\";\n if (typeof item.text === \"string\") {\n text = item.text ?? \"\";\n }\n\n const options = {\n ...additionalOptions,\n additionalContentFields: item as ContentBlock,\n };\n prompt.push(PromptTemplate.fromTemplate(text, options));\n } else if (isImageTemplateParam(item)) {\n let imgTemplate = item.image_url ?? \"\";\n let imgTemplateObject: ImagePromptTemplate<InputValues>;\n let inputVariables: string[] = [];\n if (typeof imgTemplate === \"string\") {\n let parsedTemplate: ParsedTemplateNode[];\n if (additionalOptions?.templateFormat === \"mustache\") {\n parsedTemplate = parseMustache(imgTemplate);\n } else {\n parsedTemplate = parseFString(imgTemplate);\n }\n\n const variables = parsedTemplate.flatMap((item) =>\n item.type === \"variable\" ? [item.name] : []\n );\n\n if ((variables?.length ?? 0) > 0) {\n if (variables.length > 1) {\n throw new Error(\n `Only one format variable allowed per image template.\\nGot: ${variables}\\nFrom: ${imgTemplate}`\n );\n }\n inputVariables = [variables[0]];\n } else {\n inputVariables = [];\n }\n\n imgTemplate = { url: imgTemplate };\n imgTemplateObject = new ImagePromptTemplate<InputValues>({\n template: imgTemplate,\n inputVariables,\n templateFormat: additionalOptions?.templateFormat,\n additionalContentFields: item as ContentBlock,\n });\n } else if (typeof imgTemplate === \"object\") {\n if (\"url\" in imgTemplate) {\n let parsedTemplate: ParsedTemplateNode[];\n if (additionalOptions?.templateFormat === \"mustache\") {\n parsedTemplate = parseMustache(imgTemplate.url);\n } else {\n parsedTemplate = parseFString(imgTemplate.url);\n }\n\n inputVariables = parsedTemplate.flatMap((item) =>\n item.type === \"variable\" ? [item.name] : []\n );\n } else {\n inputVariables = [];\n }\n imgTemplateObject = new ImagePromptTemplate<InputValues>({\n template: imgTemplate,\n inputVariables,\n templateFormat: additionalOptions?.templateFormat,\n additionalContentFields: item as ContentBlock,\n });\n } else {\n throw new Error(\"Invalid image template\");\n }\n prompt.push(imgTemplateObject);\n } else if (typeof item === \"object\") {\n prompt.push(\n new DictPromptTemplate({\n template: item,\n templateFormat: additionalOptions?.templateFormat,\n })\n );\n }\n }\n return new this({ prompt, additionalOptions });\n }\n\n async format(input: TypedPromptInputValues<RunInput>): Promise<BaseMessage> {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (this.prompt instanceof BaseStringPromptTemplate) {\n const text = await this.prompt.format(input);\n\n return this.createMessage(text);\n } else {\n const content: MessageContent = [];\n for (const prompt of this.prompt) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let inputs: Record<string, any> = {};\n if (!(\"inputVariables\" in prompt)) {\n throw new Error(\n `Prompt ${prompt} does not have inputVariables defined.`\n );\n }\n for (const item of prompt.inputVariables) {\n if (!inputs) {\n inputs = { [item]: input[item] };\n }\n inputs = { ...inputs, [item]: input[item] };\n }\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (prompt instanceof BaseStringPromptTemplate) {\n const formatted = await prompt.format(\n inputs as TypedPromptInputValues<RunInput>\n );\n let additionalContentFields: ContentBlock | undefined;\n if (\"additionalContentFields\" in prompt) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additionalContentFields = prompt.additionalContentFields as any;\n }\n if (formatted !== \"\") {\n content.push({\n ...additionalContentFields,\n type: \"text\",\n text: formatted,\n });\n }\n /** @TODO replace this */\n // eslint-disable-next-line no-instanceof/no-instanceof\n } else if (prompt instanceof ImagePromptTemplate) {\n const formatted = await prompt.format(\n inputs as TypedPromptInputValues<RunInput>\n );\n let additionalContentFields: ContentBlock | undefined;\n if (\"additionalContentFields\" in prompt) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additionalContentFields = prompt.additionalContentFields as any;\n }\n content.push({\n ...additionalContentFields,\n type: \"image_url\",\n image_url: formatted,\n });\n // eslint-disable-next-line no-instanceof/no-instanceof\n } else if (prompt instanceof DictPromptTemplate) {\n const formatted = await prompt.format(\n inputs as TypedPromptInputValues<RunInput>\n );\n let additionalContentFields: ContentBlock | undefined;\n if (\"additionalContentFields\" in prompt) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additionalContentFields = prompt.additionalContentFields as any;\n }\n content.push({\n ...additionalContentFields,\n ...formatted,\n } as ContentBlock);\n }\n }\n return this.createMessage(content);\n }\n }\n\n async formatMessages(values: RunInput): Promise<RunOutput> {\n return [await this.format(values)] as BaseMessage[] as RunOutput;\n }\n}\n\n/**\n * Class that represents a human message prompt template. It extends the\n * BaseMessageStringPromptTemplate.\n * @example\n * ```typescript\n * const message = HumanMessagePromptTemplate.fromTemplate(\"{text}\");\n * const formatted = await message.format({ text: \"Hello world!\" });\n *\n * const chatPrompt = ChatPromptTemplate.fromMessages([message]);\n * const formattedChatPrompt = await chatPrompt.invoke({\n * text: \"Hello world!\",\n * });\n * ```\n */\nexport class HumanMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n> extends _StringImageMessagePromptTemplate<RunInput> {\n static _messageClass(): typeof HumanMessage {\n return HumanMessage;\n }\n\n static lc_name() {\n return \"HumanMessagePromptTemplate\";\n }\n}\n\n/**\n * Class that represents an AI message prompt template. It extends the\n * BaseMessageStringPromptTemplate.\n */\nexport class AIMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n> extends _StringImageMessagePromptTemplate<RunInput> {\n static _messageClass(): typeof AIMessage {\n return AIMessage;\n }\n\n static lc_name() {\n return \"AIMessagePromptTemplate\";\n }\n}\n\n/**\n * Class that represents a system message prompt template. It extends the\n * BaseMessageStringPromptTemplate.\n * @example\n * ```typescript\n * const message = SystemMessagePromptTemplate.fromTemplate(\"{text}\");\n * const formatted = await message.format({ text: \"Hello world!\" });\n *\n * const chatPrompt = ChatPromptTemplate.fromMessages([message]);\n * const formattedChatPrompt = await chatPrompt.invoke({\n * text: \"Hello world!\",\n * });\n * ```\n */\nexport class SystemMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n> extends _StringImageMessagePromptTemplate<RunInput> {\n static _messageClass(): typeof SystemMessage {\n return SystemMessage;\n }\n\n static lc_name() {\n return \"SystemMessagePromptTemplate\";\n }\n}\n\n/**\n * Interface for the input of a ChatPromptTemplate.\n */\nexport interface ChatPromptTemplateInput<\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 BasePromptTemplateInput<RunInput, PartialVariableName> {\n /**\n * The prompt messages\n */\n promptMessages: Array<BaseMessagePromptTemplate | BaseMessage>;\n\n /**\n * Whether to try validating the template on initialization\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n\n /**\n * The formatting method to use on the prompt.\n * @default \"f-string\"\n */\n templateFormat?: TemplateFormat;\n}\n\nexport type BaseMessagePromptTemplateLike =\n | BaseMessagePromptTemplate\n | BaseMessageLike;\n\nfunction _isBaseMessagePromptTemplate(\n baseMessagePromptTemplateLike: BaseMessagePromptTemplateLike\n): baseMessagePromptTemplateLike is BaseMessagePromptTemplate {\n return (\n typeof (baseMessagePromptTemplateLike as BaseMessagePromptTemplate)\n .formatMessages === \"function\"\n );\n}\n\nfunction _coerceMessagePromptTemplateLike<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n Extra extends Omit<\n ChatPromptTemplateInput<RunInput>,\n \"inputVariables\" | \"promptMessages\" | \"partialVariables\"\n > = Omit<\n ChatPromptTemplateInput<RunInput>,\n \"inputVariables\" | \"promptMessages\" | \"partialVariables\"\n >,\n>(\n messagePromptTemplateLike: BaseMessagePromptTemplateLike,\n extra?: Extra\n): BaseMessagePromptTemplate | BaseMessage {\n if (\n _isBaseMessagePromptTemplate(messagePromptTemplateLike) ||\n isBaseMessage(messagePromptTemplateLike)\n ) {\n return messagePromptTemplateLike;\n }\n if (\n Array.isArray(messagePromptTemplateLike) &&\n messagePromptTemplateLike[0] === \"placeholder\"\n ) {\n const messageContent = messagePromptTemplateLike[1];\n if (\n extra?.templateFormat === \"mustache\" &&\n typeof messageContent === \"string\" &&\n messageContent.slice(0, 2) === \"{{\" &&\n messageContent.slice(-2) === \"}}\"\n ) {\n const variableName = messageContent.slice(2, -2);\n return new MessagesPlaceholder({ variableName, optional: true });\n } else if (\n typeof messageContent === \"string\" &&\n messageContent[0] === \"{\" &&\n messageContent[messageContent.length - 1] === \"}\"\n ) {\n const variableName = messageContent.slice(1, -1);\n return new MessagesPlaceholder({ variableName, optional: true });\n }\n throw new Error(\n `Invalid placeholder template for format ${\n extra?.templateFormat ?? `\"f-string\"`\n }: \"${\n messagePromptTemplateLike[1]\n }\". Expected a variable name surrounded by ${\n extra?.templateFormat === \"mustache\" ? \"double\" : \"single\"\n } curly braces.`\n );\n }\n const message = coerceMessageLikeToMessage(messagePromptTemplateLike);\n let templateData:\n | string\n | (\n | string\n | _TextTemplateParam\n | _ImageTemplateParam\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>\n )[];\n\n if (typeof message.content === \"string\") {\n templateData = message.content;\n } else {\n // Assuming message.content is an array of complex objects, transform it.\n templateData = message.content.map((item) => {\n if (\"text\" in item) {\n return { ...item, text: item.text };\n } else if (\"image_url\" in item) {\n return { ...item, image_url: item.image_url };\n } else {\n return item;\n }\n });\n }\n\n if (message._getType() === \"human\") {\n return HumanMessagePromptTemplate.fromTemplate(templateData, extra);\n } else if (message._getType() === \"ai\") {\n return AIMessagePromptTemplate.fromTemplate(templateData, extra);\n } else if (message._getType() === \"system\") {\n return SystemMessagePromptTemplate.fromTemplate(templateData, extra);\n } else if (ChatMessage.isInstance(message)) {\n return ChatMessagePromptTemplate.fromTemplate(\n message.content as string,\n message.role,\n extra\n );\n } else {\n throw new Error(\n `Could not coerce message prompt template from input. Received message type: \"${message._getType()}\".`\n );\n }\n}\n\nfunction isMessagesPlaceholder(\n x: BaseMessagePromptTemplate | BaseMessage\n): x is MessagesPlaceholder {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (x.constructor as any).lc_name() === \"MessagesPlaceholder\";\n}\n\n/**\n * Class that represents a chat prompt. It extends the\n * BaseChatPromptTemplate and uses an array of BaseMessagePromptTemplate\n * instances to format a series of messages for a conversation.\n * @example\n * ```typescript\n * const message = SystemMessagePromptTemplate.fromTemplate(\"{text}\");\n * const chatPrompt = ChatPromptTemplate.fromMessages([\n * [\"ai\", \"You are a helpful assistant.\"],\n * message,\n * ]);\n * const formattedChatPrompt = await chatPrompt.invoke({\n * text: \"Hello world!\",\n * });\n * ```\n */\nexport class ChatPromptTemplate<\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<RunInput, PartialVariableName>\n implements ChatPromptTemplateInput<RunInput, PartialVariableName>\n{\n static lc_name() {\n return \"ChatPromptTemplate\";\n }\n\n get lc_aliases(): Record<string, string> {\n return {\n promptMessages: \"messages\",\n };\n }\n\n promptMessages: Array<BaseMessagePromptTemplate | BaseMessage>;\n\n validateTemplate = true;\n\n templateFormat: TemplateFormat = \"f-string\";\n\n constructor(input: ChatPromptTemplateInput<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 const inputVariablesMessages = new Set<string>();\n for (const promptMessage of this.promptMessages) {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (promptMessage instanceof BaseMessage) continue;\n for (const inputVariable of promptMessage.inputVariables) {\n inputVariablesMessages.add(inputVariable);\n }\n }\n\n const totalInputVariables = this.inputVariables as string[];\n const inputVariablesInstance = new Set(\n this.partialVariables\n ? totalInputVariables.concat(Object.keys(this.partialVariables))\n : totalInputVariables\n );\n const difference = new Set(\n [...inputVariablesInstance].filter(\n (x) => !inputVariablesMessages.has(x)\n )\n );\n if (difference.size > 0) {\n throw new Error(\n `Input variables \\`${[\n ...difference,\n ]}\\` are not used in any of the prompt messages.`\n );\n }\n const otherDifference = new Set(\n [...inputVariablesMessages].filter(\n (x) => !inputVariablesInstance.has(x)\n )\n );\n if (otherDifference.size > 0) {\n throw new Error(\n `Input variables \\`${[\n ...otherDifference,\n ]}\\` are used in prompt messages but not in the prompt template.`\n );\n }\n }\n }\n\n _getPromptType(): \"chat\" {\n return \"chat\";\n }\n\n private async _parseImagePrompts(\n message: BaseMessage,\n inputValues: InputValues<\n PartialVariableName | Extract<keyof RunInput, string>\n >\n ): Promise<BaseMessage> {\n if (typeof message.content === \"string\") {\n return message;\n }\n const formattedMessageContent = await Promise.all(\n message.content.map(async (item) => {\n if (item.type !== \"image_url\") {\n return item;\n }\n\n let imageUrl = \"\";\n if (typeof item.image_url === \"string\") {\n imageUrl = item.image_url;\n } else if (\n typeof item.image_url === \"object\" &&\n item.image_url !== null &&\n \"url\" in item.image_url &&\n typeof item.image_url.url === \"string\"\n ) {\n imageUrl = item.image_url.url;\n }\n\n const promptTemplatePlaceholder = PromptTemplate.fromTemplate(\n imageUrl,\n {\n templateFormat: this.templateFormat,\n }\n );\n const formattedUrl =\n await promptTemplatePlaceholder.format(inputValues);\n\n if (\n typeof item.image_url === \"object\" &&\n item.image_url !== null &&\n \"url\" in item.image_url\n ) {\n // eslint-disable-next-line no-param-reassign\n item.image_url.url = formattedUrl;\n } else {\n item.image_url = formattedUrl;\n }\n return item;\n })\n );\n message.content = formattedMessageContent;\n return message;\n }\n\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n const allValues = await this.mergePartialAndUserVariables(values);\n let resultMessages: BaseMessage[] = [];\n\n for (const promptMessage of this.promptMessages) {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (promptMessage instanceof BaseMessage) {\n resultMessages.push(\n await this._parseImagePrompts(promptMessage, allValues)\n );\n } else {\n let inputValues: InputValues;\n\n if (this.templateFormat === \"mustache\") {\n inputValues = { ...allValues };\n } else {\n inputValues = promptMessage.inputVariables.reduce(\n (acc, inputVariable) => {\n if (\n !(inputVariable in allValues) &&\n !(\n isMessagesPlaceholder(promptMessage) && promptMessage.optional\n )\n ) {\n const error = addLangChainErrorFields(\n new Error(\n `Missing value for input variable \\`${inputVariable.toString()}\\``\n ),\n \"INVALID_PROMPT_INPUT\"\n );\n throw error;\n }\n acc[inputVariable] = allValues[inputVariable];\n return acc;\n },\n {} as InputValues\n );\n }\n const message = await promptMessage.formatMessages(inputValues);\n resultMessages = resultMessages.concat(message);\n }\n }\n return resultMessages;\n }\n\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n // This is implemented in a way it doesn't require making\n // BaseMessagePromptTemplate aware of .partial()\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 ChatPromptTemplate<\n InputValues<\n Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>\n >\n >(promptDict);\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 ): ChatPromptTemplate<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 ): ChatPromptTemplate<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 ): ChatPromptTemplate<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 ): ChatPromptTemplate<ExtractedFStringParams<T, RunInput> | InputValues> {\n const prompt = PromptTemplate.fromTemplate(template, options);\n const humanTemplate = new HumanMessagePromptTemplate({ prompt });\n return this.fromMessages<\n RunInput extends Symbol ? ParamsFromFString<T> : RunInput\n >([humanTemplate]);\n }\n\n /**\n * Create a chat model-specific prompt from individual chat messages\n * or message-like tuples.\n * @param promptMessages Messages to be passed to the chat model\n * @returns A new ChatPromptTemplate\n */\n static fromMessages<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n Extra extends\n ChatPromptTemplateInput<RunInput> = ChatPromptTemplateInput<RunInput>,\n >(\n promptMessages: (\n | ChatPromptTemplate<InputValues, string>\n | BaseMessagePromptTemplateLike\n )[],\n extra?: Omit<\n Extra,\n \"inputVariables\" | \"promptMessages\" | \"partialVariables\"\n >\n ): ChatPromptTemplate<RunInput> {\n const flattenedMessages = promptMessages.reduce(\n (acc: Array<BaseMessagePromptTemplate | BaseMessage>, promptMessage) =>\n acc.concat(\n // eslint-disable-next-line no-instanceof/no-instanceof\n promptMessage instanceof ChatPromptTemplate\n ? promptMessage.promptMessages\n : [\n _coerceMessagePromptTemplateLike<\n RunInput,\n Omit<\n Extra,\n \"inputVariables\" | \"promptMessages\" | \"partialVariables\"\n >\n >(promptMessage, extra),\n ]\n ),\n []\n );\n const flattenedPartialVariables = promptMessages.reduce(\n (acc, promptMessage) =>\n // eslint-disable-next-line no-instanceof/no-instanceof\n promptMessage instanceof ChatPromptTemplate\n ? Object.assign(acc, promptMessage.partialVariables)\n : acc,\n Object.create(null) as PartialValues\n );\n const inputVariables = new Set<string>();\n for (const promptMessage of flattenedMessages) {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (promptMessage instanceof BaseMessage) continue;\n for (const inputVariable of promptMessage.inputVariables) {\n if (inputVariable in flattenedPartialVariables) {\n continue;\n }\n inputVariables.add(inputVariable);\n }\n }\n return new this<RunInput>({\n ...extra,\n inputVariables: [...inputVariables] as Extract<keyof RunInput, string>[],\n promptMessages: flattenedMessages,\n partialVariables: flattenedPartialVariables,\n templateFormat: extra?.templateFormat,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAsB,4BAAtB,cAIUA,wBAA8B;CACtC,eAAe;EAAC;EAAkB;EAAW;CAAO;CAEpD,kBAAkB;;;;;;;CAoBlB,MAAM,OACJC,OACAC,SACoB;AACpB,SAAO,KAAK,gBACV,CAACD,YAAoB,KAAK,eAAeE,QAAM,EAC/C,OACA;GAAE,GAAG;GAAS,SAAS;EAAU,EAClC;CACF;AACF;;;;;AAcD,IAAa,sBAAb,cAIU,0BAEV;CACE,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA;CAQA,YACEC,QAGA;AACA,MAAI,OAAO,WAAW,UAEpB,SAAS,EAAE,cAAc,OAAQ;EAEnC,MAAM,OAAO;EACb,KAAK,eAAe,OAAO;EAC3B,KAAK,WAAW,OAAO,YAAY;CACpC;CAED,IAAI,i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,MAAM,oBAAoB,eAAe,OACvC,CAACC,KAAqD,kBACpD,IAAI,OAEF,yBAAyB,qBACrB,cAAc,iBACd,CACE,iCAME,eAAe,MAAM,AACxB,EACN,EACH,CAAE,EACH;EACD,MAAM,4BAA4B,eAAe,OAC/C,CAAC,KAAK,kBAEJ,yBAAyB,qBACrB,OAAO,OAAO,KAAK,cAAc,iBAAiB,GAClD,KACN,OAAO,OAAO,KAAK,CACpB;EACD,MAAM,iCAAiB,IAAI;AAC3B,OAAK,MAAM,iBAAiB,mBAAmB;AAE7C,OAAI,yBAAyBV,yBAAa;AAC1C,QAAK,MAAM,iBAAiB,cAAc,gBAAgB;AACxD,QAAI,iBAAiB,0BACnB;IAEF,eAAe,IAAI,cAAc;GAClC;EACF;AACD,SAAO,IAAI,KAAe;GACxB,GAAG;GACH,gBAAgB,CAAC,GAAG,cAAe;GACnC,gBAAgB;GAChB,kBAAkB;GAClB,gBAAgB,OAAO;EACxB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"chat.cjs","names":["Runnable","input: RunInput","options?: BaseCallbackConfig","input","fields:\n | Extract<keyof RunInput, string>\n | MessagesPlaceholderFields<Extract<keyof RunInput, string>>","values: TypedPromptInputValues<RunInput>","coerceMessageLikeToMessage","e: any","fields:\n | MessageStringPromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n | BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>,\n string\n >","BasePromptTemplate","input: BasePromptTemplateInput<RunInput, PartialVariableName>","ChatPromptValue","fields:\n | ChatMessagePromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n | BaseStringPromptTemplate<InputValues<Extract<keyof RunInput, string>>>","role?: string","values: RunInput","ChatMessage","template: T","role: string","options?: { templateFormat?: TemplateFormat }","PromptTemplate","param: unknown","fields: any","additionalOptions?: _StringImageMessagePromptTemplateOptions","inputVariables: Extract<keyof RunInput, string>[]","content: MessageContent","name: string","template:\n | string\n | Array<\n | string\n | _TextTemplateParam\n | _ImageTemplateParam\n | Record<string, unknown>\n >","prompt: Array<\n | PromptTemplate<InputValues>\n | ImagePromptTemplate<InputValues>\n | DictPromptTemplate\n >","imgTemplateObject: ImagePromptTemplate<InputValues>","inputVariables: string[]","parsedTemplate: ParsedTemplateNode[]","parseMustache","parseFString","item","ImagePromptTemplate","DictPromptTemplate","input: TypedPromptInputValues<RunInput>","BaseStringPromptTemplate","inputs: Record<string, any>","additionalContentFields: ContentBlock | undefined","HumanMessage","AIMessage","SystemMessage","baseMessagePromptTemplateLike: BaseMessagePromptTemplateLike","messagePromptTemplateLike: BaseMessagePromptTemplateLike","extra?: Extra","isBaseMessage","templateData:\n | string\n | (\n | string\n | _TextTemplateParam\n | _ImageTemplateParam\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>\n )[]","x: BaseMessagePromptTemplate | BaseMessage","input: ChatPromptTemplateInput<RunInput, PartialVariableName>","BaseMessage","message: BaseMessage","inputValues: InputValues<\n PartialVariableName | Extract<keyof RunInput, string>\n >","resultMessages: BaseMessage[]","inputValues: InputValues","addLangChainErrorFields","values: PartialValues<NewPartialVariableName>","options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >","promptMessages: (\n | ChatPromptTemplate<InputValues, string>\n | BaseMessagePromptTemplateLike\n )[]","extra?: Omit<\n Extra,\n \"inputVariables\" | \"promptMessages\" | \"partialVariables\"\n >","acc: Array<BaseMessagePromptTemplate | BaseMessage>"],"sources":["../../src/prompts/chat.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport type { BaseCallbackConfig } from \"../callbacks/manager.js\";\nimport {\n AIMessage,\n HumanMessage,\n SystemMessage,\n BaseMessage,\n ChatMessage,\n type BaseMessageLike,\n coerceMessageLikeToMessage,\n isBaseMessage,\n MessageContent,\n ContentBlock,\n} from \"../messages/index.js\";\nimport {\n type ChatPromptValueInterface,\n ChatPromptValue,\n} from \"../prompt_values.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport { Runnable } from \"../runnables/base.js\";\nimport { BaseStringPromptTemplate } from \"./string.js\";\nimport {\n BasePromptTemplate,\n type BasePromptTemplateInput,\n type TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n PromptTemplate,\n type ParamsFromFString,\n PromptTemplateInput,\n ExtractedFStringParams,\n} from \"./prompt.js\";\nimport { ImagePromptTemplate } from \"./image.js\";\nimport {\n ParsedTemplateNode,\n TemplateFormat,\n parseFString,\n parseMustache,\n} from \"./template.js\";\nimport { addLangChainErrorFields } from \"../errors/index.js\";\nimport { DictPromptTemplate } from \"./dict.js\";\n\n/**\n * Abstract class that serves as a base for creating message prompt\n * templates. It defines how to format messages for different roles in a\n * conversation.\n */\nexport abstract class BaseMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n RunOutput extends BaseMessage[] = BaseMessage[],\n> extends Runnable<RunInput, RunOutput> {\n lc_namespace = [\"langchain_core\", \"prompts\", \"chat\"];\n\n lc_serializable = true;\n\n abstract inputVariables: Array<Extract<keyof RunInput, string>>;\n\n /**\n * Method that takes an object of TypedPromptInputValues and returns a\n * promise that resolves to an array of BaseMessage instances.\n * @param values Object of TypedPromptInputValues\n * @returns Formatted array of BaseMessages\n */\n abstract formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<RunOutput>;\n\n /**\n * Calls the formatMessages method with the provided input and options.\n * @param input Input for the formatMessages method\n * @param options Optional BaseCallbackConfig\n * @returns Formatted output messages\n */\n async invoke(\n input: RunInput,\n options?: BaseCallbackConfig\n ): Promise<RunOutput> {\n return this._callWithConfig(\n (input: RunInput) => this.formatMessages(input),\n input,\n { ...options, runType: \"prompt\" }\n );\n }\n}\n\n/**\n * Interface for the fields of a MessagePlaceholder.\n */\nexport interface MessagesPlaceholderFields<T extends string> {\n variableName: T;\n optional?: boolean;\n}\n\n/**\n * Class that represents a placeholder for messages in a chat prompt. It\n * extends the BaseMessagePromptTemplate.\n */\nexport class MessagesPlaceholder<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n>\n extends BaseMessagePromptTemplate<RunInput>\n implements MessagesPlaceholderFields<Extract<keyof RunInput, string>>\n{\n static lc_name() {\n return \"MessagesPlaceholder\";\n }\n\n variableName: Extract<keyof RunInput, string>;\n\n optional: boolean;\n\n constructor(variableName: Extract<keyof RunInput, string>);\n\n constructor(\n fields: MessagesPlaceholderFields<Extract<keyof RunInput, string>>\n );\n\n constructor(\n fields:\n | Extract<keyof RunInput, string>\n | MessagesPlaceholderFields<Extract<keyof RunInput, string>>\n ) {\n if (typeof fields === \"string\") {\n // eslint-disable-next-line no-param-reassign\n fields = { variableName: fields };\n }\n super(fields);\n this.variableName = fields.variableName;\n this.optional = fields.optional ?? false;\n }\n\n get inputVariables() {\n return [this.variableName];\n }\n\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n const input = values[this.variableName];\n if (this.optional && !input) {\n return [];\n } else if (!input) {\n const error = new Error(\n `Field \"${this.variableName}\" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`\n );\n error.name = \"InputFormatError\";\n throw error;\n }\n\n let formattedMessages;\n try {\n if (Array.isArray(input)) {\n formattedMessages = input.map(coerceMessageLikeToMessage);\n } else {\n formattedMessages = [coerceMessageLikeToMessage(input)];\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n const readableInput =\n typeof input === \"string\" ? input : JSON.stringify(input, null, 2);\n const error = new Error(\n [\n `Field \"${this.variableName}\" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,\n `Received value: ${readableInput}`,\n `Additional message: ${e.message}`,\n ].join(\"\\n\\n\")\n );\n error.name = \"InputFormatError\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (error as any).lc_error_code = e.lc_error_code;\n throw error;\n }\n\n return formattedMessages;\n }\n}\n\n/**\n * Interface for the fields of a MessageStringPromptTemplate.\n */\nexport interface MessageStringPromptTemplateFields<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends InputValues = any,\n> {\n prompt: BaseStringPromptTemplate<T, string>;\n}\n\n/**\n * Abstract class that serves as a base for creating message string prompt\n * templates. It extends the BaseMessagePromptTemplate.\n */\nexport abstract class BaseMessageStringPromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n> extends BaseMessagePromptTemplate<RunInput> {\n prompt: BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>,\n string\n >;\n\n constructor(\n prompt: BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>\n >\n );\n\n constructor(\n fields: MessageStringPromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n );\n\n constructor(\n fields:\n | MessageStringPromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n | BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>,\n string\n >\n ) {\n if (!(\"prompt\" in fields)) {\n // eslint-disable-next-line no-param-reassign\n fields = { prompt: fields };\n }\n super(fields);\n this.prompt = fields.prompt;\n }\n\n get inputVariables() {\n return this.prompt.inputVariables;\n }\n\n abstract format(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage>;\n\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n return [await this.format(values)];\n }\n}\n\n/**\n * Abstract class that serves as a base for creating chat prompt\n * templates. It extends the BasePromptTemplate.\n */\nexport abstract class BaseChatPromptTemplate<\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 BasePromptTemplate<\n RunInput,\n ChatPromptValueInterface,\n PartialVariableName\n> {\n constructor(input: BasePromptTemplateInput<RunInput, PartialVariableName>) {\n super(input);\n }\n\n abstract formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]>;\n\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n return (await this.formatPromptValue(values)).toString();\n }\n\n async formatPromptValue(\n values: TypedPromptInputValues<RunInput>\n ): Promise<ChatPromptValueInterface> {\n const resultMessages = await this.formatMessages(values);\n return new ChatPromptValue(resultMessages);\n }\n}\n\n/**\n * Interface for the fields of a ChatMessagePromptTemplate.\n */\nexport interface ChatMessagePromptTemplateFields<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends InputValues = any,\n> extends MessageStringPromptTemplateFields<T> {\n role: string;\n}\n\n/**\n * Class that represents a chat message prompt template. It extends the\n * BaseMessageStringPromptTemplate.\n */\nexport class ChatMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n> extends BaseMessageStringPromptTemplate<RunInput> {\n static lc_name() {\n return \"ChatMessagePromptTemplate\";\n }\n\n role: string;\n\n constructor(\n prompt: BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>\n >,\n role: string\n );\n\n constructor(\n fields: ChatMessagePromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n );\n\n constructor(\n fields:\n | ChatMessagePromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n | BaseStringPromptTemplate<InputValues<Extract<keyof RunInput, string>>>,\n role?: string\n ) {\n if (!(\"prompt\" in fields)) {\n // eslint-disable-next-line no-param-reassign\n fields = { prompt: fields, role: role! };\n }\n super(fields);\n this.role = fields.role;\n }\n\n async format(values: RunInput): Promise<BaseMessage> {\n return new ChatMessage(await this.prompt.format(values), this.role);\n }\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(template: T, role: string, options?: { templateFormat?: TemplateFormat }) {\n return new this(\n PromptTemplate.fromTemplate<RunInput, T>(template, {\n templateFormat: options?.templateFormat,\n }),\n role\n );\n }\n}\n\ninterface _TextTemplateParam {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n text?: string | Record<string, any>;\n}\n\nfunction isTextTemplateParam(param: unknown): param is _TextTemplateParam {\n if (param === null || typeof param !== \"object\" || Array.isArray(param)) {\n return false;\n }\n return (\n Object.keys(param).length === 1 &&\n \"text\" in param &&\n typeof param.text === \"string\"\n );\n}\n\ninterface _ImageTemplateParam {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n image_url?: string | Record<string, any>;\n}\n\nfunction isImageTemplateParam(param: unknown): param is _ImageTemplateParam {\n if (param === null || typeof param !== \"object\" || Array.isArray(param)) {\n return false;\n }\n return (\n \"image_url\" in param &&\n (typeof param.image_url === \"string\" ||\n (typeof param.image_url === \"object\" &&\n param.image_url !== null &&\n \"url\" in param.image_url &&\n typeof param.image_url.url === \"string\"))\n );\n}\n\ntype MessageClass =\n | typeof HumanMessage\n | typeof AIMessage\n | typeof SystemMessage;\n\ntype ChatMessageClass = typeof ChatMessage;\n\ninterface _StringImageMessagePromptTemplateOptions<\n Format extends TemplateFormat = TemplateFormat,\n> extends Record<string, unknown> {\n templateFormat?: Format;\n}\n\nclass _StringImageMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n RunOutput extends BaseMessage[] = BaseMessage[],\n> extends BaseMessagePromptTemplate<RunInput, RunOutput> {\n lc_namespace = [\"langchain_core\", \"prompts\", \"chat\"];\n\n lc_serializable = true;\n\n inputVariables: Array<Extract<keyof RunInput, string>> = [];\n\n additionalOptions: _StringImageMessagePromptTemplateOptions = {};\n\n prompt:\n | BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>,\n string\n >\n | Array<\n | BaseStringPromptTemplate<\n InputValues<Extract<keyof RunInput, string>>,\n string\n >\n | ImagePromptTemplate<\n InputValues<Extract<keyof RunInput, string>>,\n string\n >\n | MessageStringPromptTemplateFields<\n InputValues<Extract<keyof RunInput, string>>\n >\n | DictPromptTemplate<InputValues<Extract<keyof RunInput, string>>>\n >;\n\n protected messageClass?: MessageClass;\n\n static _messageClass(): MessageClass {\n throw new Error(\n \"Can not invoke _messageClass from inside _StringImageMessagePromptTemplate\"\n );\n }\n\n // ChatMessage contains role field, others don't.\n // Because of this, we have a separate class property for ChatMessage.\n protected chatMessageClass?: ChatMessageClass;\n\n constructor(\n /** @TODO When we come up with a better way to type prompt templates, fix this */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n fields: any,\n additionalOptions?: _StringImageMessagePromptTemplateOptions\n ) {\n if (!(\"prompt\" in fields)) {\n // eslint-disable-next-line no-param-reassign\n fields = { prompt: fields };\n }\n super(fields);\n this.prompt = fields.prompt;\n if (Array.isArray(this.prompt)) {\n let inputVariables: Extract<keyof RunInput, string>[] = [];\n this.prompt.forEach((prompt) => {\n if (\"inputVariables\" in prompt) {\n inputVariables = inputVariables.concat(prompt.inputVariables);\n }\n });\n this.inputVariables = inputVariables;\n } else {\n this.inputVariables = this.prompt.inputVariables;\n }\n this.additionalOptions = additionalOptions ?? this.additionalOptions;\n }\n\n createMessage(content: MessageContent) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const constructor = this.constructor as any;\n if (constructor._messageClass()) {\n const MsgClass = constructor._messageClass();\n return new MsgClass({ content });\n } else if (constructor.chatMessageClass) {\n const MsgClass = constructor.chatMessageClass();\n // Assuming ChatMessage constructor also takes a content argument\n return new MsgClass({\n content,\n role: this.getRoleFromMessageClass(MsgClass.lc_name()),\n });\n } else {\n throw new Error(\"No message class defined\");\n }\n }\n\n getRoleFromMessageClass(name: string) {\n switch (name) {\n case \"HumanMessage\":\n return \"human\";\n case \"AIMessage\":\n return \"ai\";\n case \"SystemMessage\":\n return \"system\";\n case \"ChatMessage\":\n return \"chat\";\n default:\n throw new Error(\"Invalid message class name\");\n }\n }\n\n static fromTemplate(\n template:\n | string\n | Array<\n | string\n | _TextTemplateParam\n | _ImageTemplateParam\n | Record<string, unknown>\n >,\n additionalOptions?: _StringImageMessagePromptTemplateOptions\n ) {\n if (typeof template === \"string\") {\n return new this(PromptTemplate.fromTemplate(template, additionalOptions));\n }\n const prompt: Array<\n | PromptTemplate<InputValues>\n | ImagePromptTemplate<InputValues>\n | DictPromptTemplate\n > = [];\n for (const item of template) {\n // handle string cases\n if (typeof item === \"string\") {\n prompt.push(PromptTemplate.fromTemplate(item, additionalOptions));\n } else if (item === null) {\n // pass\n } else if (isTextTemplateParam(item)) {\n let text = \"\";\n if (typeof item.text === \"string\") {\n text = item.text ?? \"\";\n }\n\n const options = {\n ...additionalOptions,\n additionalContentFields: item as ContentBlock,\n };\n prompt.push(PromptTemplate.fromTemplate(text, options));\n } else if (isImageTemplateParam(item)) {\n let imgTemplate = item.image_url ?? \"\";\n let imgTemplateObject: ImagePromptTemplate<InputValues>;\n let inputVariables: string[] = [];\n if (typeof imgTemplate === \"string\") {\n let parsedTemplate: ParsedTemplateNode[];\n if (additionalOptions?.templateFormat === \"mustache\") {\n parsedTemplate = parseMustache(imgTemplate);\n } else {\n parsedTemplate = parseFString(imgTemplate);\n }\n\n const variables = parsedTemplate.flatMap((item) =>\n item.type === \"variable\" ? [item.name] : []\n );\n\n if ((variables?.length ?? 0) > 0) {\n if (variables.length > 1) {\n throw new Error(\n `Only one format variable allowed per image template.\\nGot: ${variables}\\nFrom: ${imgTemplate}`\n );\n }\n inputVariables = [variables[0]];\n } else {\n inputVariables = [];\n }\n\n imgTemplate = { url: imgTemplate };\n imgTemplateObject = new ImagePromptTemplate<InputValues>({\n template: imgTemplate,\n inputVariables,\n templateFormat: additionalOptions?.templateFormat,\n additionalContentFields: item as ContentBlock,\n });\n } else if (typeof imgTemplate === \"object\") {\n if (\"url\" in imgTemplate) {\n let parsedTemplate: ParsedTemplateNode[];\n if (additionalOptions?.templateFormat === \"mustache\") {\n parsedTemplate = parseMustache(imgTemplate.url);\n } else {\n parsedTemplate = parseFString(imgTemplate.url);\n }\n\n inputVariables = parsedTemplate.flatMap((item) =>\n item.type === \"variable\" ? [item.name] : []\n );\n } else {\n inputVariables = [];\n }\n imgTemplateObject = new ImagePromptTemplate<InputValues>({\n template: imgTemplate,\n inputVariables,\n templateFormat: additionalOptions?.templateFormat,\n additionalContentFields: item as ContentBlock,\n });\n } else {\n throw new Error(\"Invalid image template\");\n }\n prompt.push(imgTemplateObject);\n } else if (typeof item === \"object\") {\n prompt.push(\n new DictPromptTemplate({\n template: item,\n templateFormat: additionalOptions?.templateFormat,\n })\n );\n }\n }\n return new this({ prompt, additionalOptions });\n }\n\n async format(input: TypedPromptInputValues<RunInput>): Promise<BaseMessage> {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (this.prompt instanceof BaseStringPromptTemplate) {\n const text = await this.prompt.format(input);\n\n return this.createMessage(text);\n } else {\n const content: MessageContent = [];\n for (const prompt of this.prompt) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let inputs: Record<string, any> = {};\n if (!(\"inputVariables\" in prompt)) {\n throw new Error(\n `Prompt ${prompt} does not have inputVariables defined.`\n );\n }\n for (const item of prompt.inputVariables) {\n if (!inputs) {\n inputs = { [item]: input[item] };\n }\n inputs = { ...inputs, [item]: input[item] };\n }\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (prompt instanceof BaseStringPromptTemplate) {\n const formatted = await prompt.format(\n inputs as TypedPromptInputValues<RunInput>\n );\n let additionalContentFields: ContentBlock | undefined;\n if (\"additionalContentFields\" in prompt) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additionalContentFields = prompt.additionalContentFields as any;\n }\n if (formatted !== \"\") {\n content.push({\n ...additionalContentFields,\n type: \"text\",\n text: formatted,\n });\n }\n /** @TODO replace this */\n // eslint-disable-next-line no-instanceof/no-instanceof\n } else if (prompt instanceof ImagePromptTemplate) {\n const formatted = await prompt.format(\n inputs as TypedPromptInputValues<RunInput>\n );\n let additionalContentFields: ContentBlock | undefined;\n if (\"additionalContentFields\" in prompt) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additionalContentFields = prompt.additionalContentFields as any;\n }\n content.push({\n ...additionalContentFields,\n type: \"image_url\",\n image_url: formatted,\n });\n // eslint-disable-next-line no-instanceof/no-instanceof\n } else if (prompt instanceof DictPromptTemplate) {\n const formatted = await prompt.format(\n inputs as TypedPromptInputValues<RunInput>\n );\n let additionalContentFields: ContentBlock | undefined;\n if (\"additionalContentFields\" in prompt) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additionalContentFields = prompt.additionalContentFields as any;\n }\n content.push({\n ...additionalContentFields,\n ...formatted,\n } as ContentBlock);\n }\n }\n return this.createMessage(content);\n }\n }\n\n async formatMessages(values: RunInput): Promise<RunOutput> {\n return [await this.format(values)] as BaseMessage[] as RunOutput;\n }\n}\n\n/**\n * Class that represents a human message prompt template. It extends the\n * BaseMessageStringPromptTemplate.\n * @example\n * ```typescript\n * const message = HumanMessagePromptTemplate.fromTemplate(\"{text}\");\n * const formatted = await message.format({ text: \"Hello world!\" });\n *\n * const chatPrompt = ChatPromptTemplate.fromMessages([message]);\n * const formattedChatPrompt = await chatPrompt.invoke({\n * text: \"Hello world!\",\n * });\n * ```\n */\nexport class HumanMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n> extends _StringImageMessagePromptTemplate<RunInput> {\n static _messageClass(): typeof HumanMessage {\n return HumanMessage;\n }\n\n static lc_name() {\n return \"HumanMessagePromptTemplate\";\n }\n}\n\n/**\n * Class that represents an AI message prompt template. It extends the\n * BaseMessageStringPromptTemplate.\n */\nexport class AIMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n> extends _StringImageMessagePromptTemplate<RunInput> {\n static _messageClass(): typeof AIMessage {\n return AIMessage;\n }\n\n static lc_name() {\n return \"AIMessagePromptTemplate\";\n }\n}\n\n/**\n * Class that represents a system message prompt template. It extends the\n * BaseMessageStringPromptTemplate.\n * @example\n * ```typescript\n * const message = SystemMessagePromptTemplate.fromTemplate(\"{text}\");\n * const formatted = await message.format({ text: \"Hello world!\" });\n *\n * const chatPrompt = ChatPromptTemplate.fromMessages([message]);\n * const formattedChatPrompt = await chatPrompt.invoke({\n * text: \"Hello world!\",\n * });\n * ```\n */\nexport class SystemMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n> extends _StringImageMessagePromptTemplate<RunInput> {\n static _messageClass(): typeof SystemMessage {\n return SystemMessage;\n }\n\n static lc_name() {\n return \"SystemMessagePromptTemplate\";\n }\n}\n\n/**\n * Interface for the input of a ChatPromptTemplate.\n */\nexport interface ChatPromptTemplateInput<\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 BasePromptTemplateInput<RunInput, PartialVariableName> {\n /**\n * The prompt messages\n */\n promptMessages: Array<BaseMessagePromptTemplate | BaseMessage>;\n\n /**\n * Whether to try validating the template on initialization\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n\n /**\n * The formatting method to use on the prompt.\n * @default \"f-string\"\n */\n templateFormat?: TemplateFormat;\n}\n\nexport type BaseMessagePromptTemplateLike =\n | BaseMessagePromptTemplate\n | BaseMessageLike;\n\nfunction _isBaseMessagePromptTemplate(\n baseMessagePromptTemplateLike: BaseMessagePromptTemplateLike\n): baseMessagePromptTemplateLike is BaseMessagePromptTemplate {\n return (\n typeof (baseMessagePromptTemplateLike as BaseMessagePromptTemplate)\n .formatMessages === \"function\"\n );\n}\n\nfunction _coerceMessagePromptTemplateLike<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n Extra extends Omit<\n ChatPromptTemplateInput<RunInput>,\n \"inputVariables\" | \"promptMessages\" | \"partialVariables\"\n > = Omit<\n ChatPromptTemplateInput<RunInput>,\n \"inputVariables\" | \"promptMessages\" | \"partialVariables\"\n >,\n>(\n messagePromptTemplateLike: BaseMessagePromptTemplateLike,\n extra?: Extra\n): BaseMessagePromptTemplate | BaseMessage {\n if (\n _isBaseMessagePromptTemplate(messagePromptTemplateLike) ||\n isBaseMessage(messagePromptTemplateLike)\n ) {\n return messagePromptTemplateLike;\n }\n if (\n Array.isArray(messagePromptTemplateLike) &&\n messagePromptTemplateLike[0] === \"placeholder\"\n ) {\n const messageContent = messagePromptTemplateLike[1];\n if (\n extra?.templateFormat === \"mustache\" &&\n typeof messageContent === \"string\" &&\n messageContent.slice(0, 2) === \"{{\" &&\n messageContent.slice(-2) === \"}}\"\n ) {\n const variableName = messageContent.slice(2, -2);\n return new MessagesPlaceholder({ variableName, optional: true });\n } else if (\n typeof messageContent === \"string\" &&\n messageContent[0] === \"{\" &&\n messageContent[messageContent.length - 1] === \"}\"\n ) {\n const variableName = messageContent.slice(1, -1);\n return new MessagesPlaceholder({ variableName, optional: true });\n }\n throw new Error(\n `Invalid placeholder template for format ${\n extra?.templateFormat ?? `\"f-string\"`\n }: \"${\n messagePromptTemplateLike[1]\n }\". Expected a variable name surrounded by ${\n extra?.templateFormat === \"mustache\" ? \"double\" : \"single\"\n } curly braces.`\n );\n }\n const message = coerceMessageLikeToMessage(messagePromptTemplateLike);\n let templateData:\n | string\n | (\n | string\n | _TextTemplateParam\n | _ImageTemplateParam\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>\n )[];\n\n if (typeof message.content === \"string\") {\n templateData = message.content;\n } else {\n // Assuming message.content is an array of complex objects, transform it.\n templateData = message.content.map((item) => {\n if (\"text\" in item) {\n return { ...item, text: item.text };\n } else if (\"image_url\" in item) {\n return { ...item, image_url: item.image_url };\n } else {\n return item;\n }\n });\n }\n\n if (message._getType() === \"human\") {\n return HumanMessagePromptTemplate.fromTemplate(templateData, extra);\n } else if (message._getType() === \"ai\") {\n return AIMessagePromptTemplate.fromTemplate(templateData, extra);\n } else if (message._getType() === \"system\") {\n return SystemMessagePromptTemplate.fromTemplate(templateData, extra);\n } else if (ChatMessage.isInstance(message)) {\n return ChatMessagePromptTemplate.fromTemplate(\n message.content as string,\n message.role,\n extra\n );\n } else {\n throw new Error(\n `Could not coerce message prompt template from input. Received message type: \"${message._getType()}\".`\n );\n }\n}\n\nfunction isMessagesPlaceholder(\n x: BaseMessagePromptTemplate | BaseMessage\n): x is MessagesPlaceholder {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (x.constructor as any).lc_name() === \"MessagesPlaceholder\";\n}\n\n/**\n * Class that represents a chat prompt. It extends the\n * BaseChatPromptTemplate and uses an array of BaseMessagePromptTemplate\n * instances to format a series of messages for a conversation.\n * @example\n * ```typescript\n * const message = SystemMessagePromptTemplate.fromTemplate(\"{text}\");\n * const chatPrompt = ChatPromptTemplate.fromMessages([\n * [\"ai\", \"You are a helpful assistant.\"],\n * message,\n * ]);\n * const formattedChatPrompt = await chatPrompt.invoke({\n * text: \"Hello world!\",\n * });\n * ```\n */\nexport class ChatPromptTemplate<\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<RunInput, PartialVariableName>\n implements ChatPromptTemplateInput<RunInput, PartialVariableName>\n{\n static lc_name() {\n return \"ChatPromptTemplate\";\n }\n\n get lc_aliases(): Record<string, string> {\n return {\n promptMessages: \"messages\",\n };\n }\n\n promptMessages: Array<BaseMessagePromptTemplate | BaseMessage>;\n\n validateTemplate = true;\n\n templateFormat: TemplateFormat = \"f-string\";\n\n constructor(input: ChatPromptTemplateInput<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 const inputVariablesMessages = new Set<string>();\n for (const promptMessage of this.promptMessages) {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (promptMessage instanceof BaseMessage) continue;\n for (const inputVariable of promptMessage.inputVariables) {\n inputVariablesMessages.add(inputVariable);\n }\n }\n\n const totalInputVariables = this.inputVariables as string[];\n const inputVariablesInstance = new Set(\n this.partialVariables\n ? totalInputVariables.concat(Object.keys(this.partialVariables))\n : totalInputVariables\n );\n const difference = new Set(\n [...inputVariablesInstance].filter(\n (x) => !inputVariablesMessages.has(x)\n )\n );\n if (difference.size > 0) {\n throw new Error(\n `Input variables \\`${[\n ...difference,\n ]}\\` are not used in any of the prompt messages.`\n );\n }\n const otherDifference = new Set(\n [...inputVariablesMessages].filter(\n (x) => !inputVariablesInstance.has(x)\n )\n );\n if (otherDifference.size > 0) {\n throw new Error(\n `Input variables \\`${[\n ...otherDifference,\n ]}\\` are used in prompt messages but not in the prompt template.`\n );\n }\n }\n }\n\n _getPromptType(): \"chat\" {\n return \"chat\";\n }\n\n private async _parseImagePrompts(\n message: BaseMessage,\n inputValues: InputValues<\n PartialVariableName | Extract<keyof RunInput, string>\n >\n ): Promise<BaseMessage> {\n if (typeof message.content === \"string\") {\n return message;\n }\n const formattedMessageContent = await Promise.all(\n message.content.map(async (item) => {\n if (item.type !== \"image_url\") {\n return item;\n }\n\n let imageUrl = \"\";\n if (typeof item.image_url === \"string\") {\n imageUrl = item.image_url;\n } else if (\n typeof item.image_url === \"object\" &&\n item.image_url !== null &&\n \"url\" in item.image_url &&\n typeof item.image_url.url === \"string\"\n ) {\n imageUrl = item.image_url.url;\n }\n\n const promptTemplatePlaceholder = PromptTemplate.fromTemplate(\n imageUrl,\n {\n templateFormat: this.templateFormat,\n }\n );\n const formattedUrl =\n await promptTemplatePlaceholder.format(inputValues);\n\n if (\n typeof item.image_url === \"object\" &&\n item.image_url !== null &&\n \"url\" in item.image_url\n ) {\n // eslint-disable-next-line no-param-reassign\n item.image_url.url = formattedUrl;\n } else {\n item.image_url = formattedUrl;\n }\n return item;\n })\n );\n message.content = formattedMessageContent;\n return message;\n }\n\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n const allValues = await this.mergePartialAndUserVariables(values);\n let resultMessages: BaseMessage[] = [];\n\n for (const promptMessage of this.promptMessages) {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (promptMessage instanceof BaseMessage) {\n resultMessages.push(\n await this._parseImagePrompts(promptMessage, allValues)\n );\n } else {\n let inputValues: InputValues;\n\n if (this.templateFormat === \"mustache\") {\n inputValues = { ...allValues };\n } else {\n inputValues = promptMessage.inputVariables.reduce(\n (acc, inputVariable) => {\n if (\n !(inputVariable in allValues) &&\n !(\n isMessagesPlaceholder(promptMessage) && promptMessage.optional\n )\n ) {\n const error = addLangChainErrorFields(\n new Error(\n `Missing value for input variable \\`${inputVariable.toString()}\\``\n ),\n \"INVALID_PROMPT_INPUT\"\n );\n throw error;\n }\n acc[inputVariable] = allValues[inputVariable];\n return acc;\n },\n {} as InputValues\n );\n }\n const message = await promptMessage.formatMessages(inputValues);\n resultMessages = resultMessages.concat(message);\n }\n }\n return resultMessages;\n }\n\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n // This is implemented in a way it doesn't require making\n // BaseMessagePromptTemplate aware of .partial()\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 ChatPromptTemplate<\n InputValues<\n Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>\n >\n >(promptDict);\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 ): ChatPromptTemplate<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 ): ChatPromptTemplate<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 ): ChatPromptTemplate<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 ): ChatPromptTemplate<ExtractedFStringParams<T, RunInput> | InputValues> {\n const prompt = PromptTemplate.fromTemplate(template, options);\n const humanTemplate = new HumanMessagePromptTemplate({ prompt });\n return this.fromMessages<\n RunInput extends Symbol ? ParamsFromFString<T> : RunInput\n >([humanTemplate]);\n }\n\n /**\n * Create a chat model-specific prompt from individual chat messages\n * or message-like tuples.\n * @param promptMessages Messages to be passed to the chat model\n * @returns A new ChatPromptTemplate\n */\n static fromMessages<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n Extra extends ChatPromptTemplateInput<RunInput> =\n ChatPromptTemplateInput<RunInput>,\n >(\n promptMessages: (\n | ChatPromptTemplate<InputValues, string>\n | BaseMessagePromptTemplateLike\n )[],\n extra?: Omit<\n Extra,\n \"inputVariables\" | \"promptMessages\" | \"partialVariables\"\n >\n ): ChatPromptTemplate<RunInput> {\n const flattenedMessages = promptMessages.reduce(\n (acc: Array<BaseMessagePromptTemplate | BaseMessage>, promptMessage) =>\n acc.concat(\n // eslint-disable-next-line no-instanceof/no-instanceof\n promptMessage instanceof ChatPromptTemplate\n ? promptMessage.promptMessages\n : [\n _coerceMessagePromptTemplateLike<\n RunInput,\n Omit<\n Extra,\n \"inputVariables\" | \"promptMessages\" | \"partialVariables\"\n >\n >(promptMessage, extra),\n ]\n ),\n []\n );\n const flattenedPartialVariables = promptMessages.reduce(\n (acc, promptMessage) =>\n // eslint-disable-next-line no-instanceof/no-instanceof\n promptMessage instanceof ChatPromptTemplate\n ? Object.assign(acc, promptMessage.partialVariables)\n : acc,\n Object.create(null) as PartialValues\n );\n const inputVariables = new Set<string>();\n for (const promptMessage of flattenedMessages) {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (promptMessage instanceof BaseMessage) continue;\n for (const inputVariable of promptMessage.inputVariables) {\n if (inputVariable in flattenedPartialVariables) {\n continue;\n }\n inputVariables.add(inputVariable);\n }\n }\n return new this<RunInput>({\n ...extra,\n inputVariables: [...inputVariables] as Extract<keyof RunInput, string>[],\n promptMessages: flattenedMessages,\n partialVariables: flattenedPartialVariables,\n templateFormat: extra?.templateFormat,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAsB,4BAAtB,cAIUA,wBAA8B;CACtC,eAAe;EAAC;EAAkB;EAAW;CAAO;CAEpD,kBAAkB;;;;;;;CAoBlB,MAAM,OACJC,OACAC,SACoB;AACpB,SAAO,KAAK,gBACV,CAACD,YAAoB,KAAK,eAAeE,QAAM,EAC/C,OACA;GAAE,GAAG;GAAS,SAAS;EAAU,EAClC;CACF;AACF;;;;;AAcD,IAAa,sBAAb,cAIU,0BAEV;CACE,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA;CAQA,YACEC,QAGA;AACA,MAAI,OAAO,WAAW,UAEpB,SAAS,EAAE,cAAc,OAAQ;EAEnC,MAAM,OAAO;EACb,KAAK,eAAe,OAAO;EAC3B,KAAK,WAAW,OAAO,YAAY;CACpC;CAED,IAAI,iBAAiB;AACnB,SAAO,CAAC,KAAK,YAAa;CAC3B;CAED,MAAM,eACJC,QACwB;EACxB,MAAM,QAAQ,OAAO,KAAK;AAC1B,MAAI,KAAK,YAAY,CAAC,MAC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