@langchain/core 1.1.19 → 1.1.20
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 +6 -0
- package/dist/caches/index.d.cts.map +1 -1
- package/dist/callbacks/base.cjs.map +1 -1
- package/dist/callbacks/base.d.cts.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/language_models/chat_models.d.cts.map +1 -1
- package/dist/load/serializable.cjs.map +1 -1
- package/dist/load/serializable.js.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/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 +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message.js","names":["message: unknown"],"sources":["../../src/messages/message.ts"],"sourcesContent":["import type { ContentBlock } from \"./content/index.js\";\nimport type { ResponseMetadata, UsageMetadata } from \"./metadata.js\";\nimport type { $MergeDiscriminatedUnion, $MergeObjects } from \"./utils.js\";\n\n/**\n * Represents the possible types of messages in the system.\n * Includes standard message types (\"ai\", \"human\", \"tool\", \"system\")\n * and allows for custom string types that are non-null.\n *\n * @example\n * ```ts\n * // Standard message types\n * const messageType1: MessageType = \"ai\";\n * const messageType2: MessageType = \"human\";\n *\n * // Custom message type\n * const messageType3: MessageType = \"custom_type\";\n * ```\n */\nexport type MessageType =\n | \"ai\"\n | \"human\"\n | \"tool\"\n | \"system\"\n | (string & NonNullable<unknown>);\n\n/**\n * Represents the output version format for message content.\n *\n * This type determines how the content field is structured in a message:\n * - \"v0\": Content is represented as a simple string or array of content blocks\n * - provides backward compatibility with simpler content representations\n * - \"v1\": Content follows the structured ContentBlock format with typed discriminated unions\n * - enables full type safety and structured content block handling\n *\n * @example\n * ```ts\n * // v0 format - simple content representation\n * const v0Message: Message<{ outputVersion: \"v0\", content: ... }> = {\n * type: \"human\",\n * content: \"Hello world\" // string | Array<ContentBlock | ContentBlock.Text>\n * };\n *\n * // v1 format - structured content blocks\n * const v1Message: Message<{ outputVersion: \"v1\", content: ... }> = {\n * type: \"human\",\n * content: [\n * { type: \"text\", text: \"Hello world\" },\n * { type: \"image\", image_url: \"...\" }\n * ] // Array<ContentBlock | ...> (determined by the structure)\n * };\n * ```\n */\nexport type MessageOutputVersion = \"v0\" | \"v1\";\n\n/**\n * Represents the input and output types of a tool that can be used in messages.\n *\n * @template TInput - The type of input the tool accepts.\n * @template TOutput - The type of output the tool produces.\n *\n * @example\n * ```ts\n * // Tool that takes a string input and returns a number\n * interface StringToNumberTool extends MessageToolDefinition<string, number> {\n * input: string;\n * output: number;\n * }\n * ```\n */\nexport interface MessageToolDefinition<TInput = unknown, TOutput = unknown> {\n input: TInput;\n output: TOutput;\n}\n\n/**\n * Represents a structured set of tools by mapping tool names to definitions\n * that can be used in messages.\n *\n * @example\n * ```ts\n * interface MyToolSet extends MessageToolSet {\n * calculator: MessageToolDefinition<\n * { operation: string; numbers: number[] },\n * number\n * >;\n * translator: MessageToolDefinition<\n * { text: string; targetLanguage: string },\n * string\n * >;\n * }\n * ```\n */\nexport interface MessageToolSet {\n [key: string]: MessageToolDefinition;\n}\n\n/**\n * Represents a tool call block within a message structure by mapping tool names to their\n * corresponding tool call formats, including the input arguments and an optional identifier.\n *\n * @template TStructure - A message structure type that may contain tool definitions\n *\n * @example\n * ```ts\n * // Given a message structure with a calculator tool:\n * interface MyStructure extends MessageStructure {\n * tools: {\n * calculator: MessageToolDefinition<{ operation: string, numbers: number[] }, number>\n * }\n * }\n *\n * // The tool call block would be:\n * type CalcToolCall = $MessageToolCallBlock<MyStructure>;\n * // Resolves to:\n * // {\n * // type: \"tool_call\";\n * // name: \"calculator\";\n * // args: { operation: string, numbers: number[] };\n * // id?: string;\n * // }\n * ```\n */\nexport type $MessageToolCallBlock<TStructure extends MessageStructure> =\n TStructure[\"tools\"] extends MessageToolSet\n ? {\n [K in keyof TStructure[\"tools\"]]: K extends string\n ? TStructure[\"tools\"][K] extends MessageToolDefinition\n ? ContentBlock.Tools.ToolCall<K, TStructure[\"tools\"][K][\"input\"]>\n : never\n : never;\n }[keyof TStructure[\"tools\"]]\n : never;\n\n/**\n * Helper type to infer a union of ToolCall types from the tools defined in a MessageStructure.\n * This is used to type the `tool_calls` array in AIMessage based on the available tools.\n *\n * @template TStructure - A message structure type that may contain tool definitions\n *\n * @example\n * ```ts\n * // Given a message structure with tools:\n * interface MyStructure extends MessageStructure {\n * tools: {\n * calculator: MessageToolDefinition<{ a: number, b: number }, number>;\n * search: MessageToolDefinition<{ query: string }, string[]>;\n * }\n * }\n *\n * // The inferred tool calls would be:\n * type ToolCalls = $InferToolCalls<MyStructure>;\n * // Resolves to:\n * // | { type?: \"tool_call\"; id?: string; name: \"calculator\"; args: { a: number, b: number } }\n * // | { type?: \"tool_call\"; id?: string; name: \"search\"; args: { query: string } }\n * ```\n */\nexport type $InferToolCalls<TStructure extends MessageStructure> =\n NonNullable<TStructure[\"tools\"]> extends MessageToolSet\n ? NonNullable<TStructure[\"tools\"]> extends infer TTools extends\n MessageToolSet\n ? {\n [K in keyof TTools]: K extends string\n ? TTools[K] extends MessageToolDefinition\n ? {\n readonly type?: \"tool_call\";\n id?: string;\n name: K;\n // Fallback to Record<string, any> when input is unknown\n args: [unknown] extends [TTools[K][\"input\"]]\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Record<string, any>\n : TTools[K][\"input\"];\n }\n : never\n : never;\n }[keyof TTools]\n : never\n : {\n readonly type?: \"tool_call\";\n id?: string;\n name: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: Record<string, any>;\n };\n\n/**\n * Helper type to infer a union of tool output types from the tools defined in a MessageStructure.\n * This is used to type the `content` of ToolMessage based on the available tool outputs.\n *\n * @template TStructure - A message structure type that may contain tool definitions\n *\n * @example\n * ```ts\n * // Given a message structure with tools:\n * interface MyStructure extends MessageStructure {\n * tools: {\n * calculator: MessageToolDefinition<{ a: number, b: number }, number>;\n * search: MessageToolDefinition<{ query: string }, string[]>;\n * }\n * }\n *\n * // The inferred tool outputs would be:\n * type ToolOutputs = $InferToolOutputs<MyStructure>;\n * // Resolves to: number | string[]\n * ```\n */\nexport type $InferToolOutputs<TStructure extends MessageStructure> =\n NonNullable<TStructure[\"tools\"]> extends MessageToolSet\n ? NonNullable<TStructure[\"tools\"]> extends infer TTools extends\n MessageToolSet\n ? {\n [K in keyof TTools]: TTools[K] extends MessageToolDefinition\n ? TTools[K][\"output\"]\n : never;\n }[keyof TTools]\n : unknown\n : unknown;\n\n/**\n * Core interface that defines the structure of messages.\n *\n * @example\n * ```ts\n * // Basic message structure with just content blocks\n * interface SimpleMessageStructure extends MessageStructure {\n * content: {\n * human: ContentBlock.Text;\n * // allows for text + reasoning blocks in ai messages\n * ai: ContentBlock.Text | ContentBlock.Reasoning;\n * }\n * }\n *\n * // Message structure with tools and properties\n * interface AdvancedMessageStructure extends MessageStructure {\n * tools: {\n * calculator: MessageToolDefinition<\n * { operation: string; numbers: number[] },\n * number\n * >;\n * };\n * content: {\n * // allows for text + image blocks in human messages\n * human: ContentBlock.Text | ContentBlock.Multimodal.Image;\n * // only allows for text blocks in ai messages\n * ai: ContentBlock.Text;\n * };\n * properties: {\n * // pins properties to ai messages\n * ai: {\n * response_metadata: {\n * confidence: number;\n * model: string;\n * };\n * };\n * }\n * }\n *\n * // Using with $MergeMessageStructure to combine structures\n * // The resulting type when passed into BaseMessage will have a calculator tool,\n * // allow for text + image blocks in human messages,\n * // and text + reasoning blocks + additional arbitrary properties in ai messages.\n * type CombinedStructure = $MergeMessageStructure<\n * SimpleMessageStructure,\n * AdvancedMessageStructure\n * >;\n *\n * // Using in a Message object\n * const message: Message<CombinedStructure> = {\n * id: \"msg-123\",\n * type: \"human\",\n * content: [\n * { type: \"text\", text: \"Hello!\" }\n * { type: \"image\", mimeType: \"image/jpeg\", url: \"https://example.com/image.jpg\" }\n * // this block will throw an error because it's not defined in the structure\n * { type: \"reasoning\", reasoning: \"The answer is 42\" }\n * ]\n * };\n * ```\n */\nexport interface MessageStructure<\n TTools extends MessageToolSet = MessageToolSet,\n> {\n /**\n * Optional output version for the message structure.\n * If not provided, defaults to \"v0\".\n */\n readonly outputVersion?: MessageOutputVersion;\n /**\n * Optional set of tool definitions that can be used in messages.\n * Each tool is defined with input/output types and can be referenced in tool messages.\n */\n readonly tools?: TTools;\n /**\n * Optional mapping of message types to their allowed content blocks.\n * Each message type can specify what content block types it supports (text, images, etc).\n */\n readonly content?: Partial<{\n [key in MessageType]: ContentBlock;\n }>;\n /**\n * Optional mapping of message types to arbitrary property objects.\n * Allows attaching custom metadata or other information to specific message types.\n */\n readonly properties?: Partial<{\n [key in MessageType]: Record<string, unknown>;\n }>;\n}\n\n/**\n * Normalizes an arbitrary type to a message output version or undefined.\n * Accepts unknown and narrows to a valid MessageOutputVersion if present.\n */\ntype $NormalizeMessageOutputVersion<T> =\n | Extract<T, MessageOutputVersion>\n | undefined;\n\n/**\n * Merges two output version types from message structures.\n *\n * This utility type determines the resulting output version when combining two message structures.\n * The merge logic follows these rules:\n *\n * - If both T and U are undefined, defaults to \"v0\" for backwards compatibility\n * - If T is undefined but U is defined, uses U's version\n * - If U is undefined but T is defined, uses T's version\n * - If both T and U are defined, U takes precedence (later structure wins)\n *\n * @template T - The output version from the first message structure\n * @template U - The output version from the second message structure\n *\n * @example\n * ```ts\n * // Both undefined - defaults to \"v0\"\n * type Result1 = $MergeOutputVersion<undefined, undefined>; // \"v0\"\n *\n * // One defined - uses the defined version\n * type Result2 = $MergeOutputVersion<undefined, \"v1\">; // \"v1\"\n * type Result3 = $MergeOutputVersion<\"v0\", undefined>; // \"v0\"\n *\n * // Both defined - second takes precedence\n * type Result4 = $MergeOutputVersion<\"v0\", \"v1\">; // \"v1\"\n * ```\n */\nexport type $MergeOutputVersion<T, U> =\n $NormalizeMessageOutputVersion<T> extends infer TV\n ? $NormalizeMessageOutputVersion<U> extends infer UV\n ? [TV, UV] extends [undefined, undefined]\n ? \"v0\"\n : [TV] extends [undefined]\n ? Exclude<UV, undefined>\n : [UV] extends [undefined]\n ? Exclude<TV, undefined>\n : UV\n : never\n : never;\n\n/**\n * Merges two content definition objects from message structures.\n *\n * This utility type combines content definitions from two message structures, handling\n * the merging of content block types for each message type. The merge logic follows\n * these rules:\n *\n * - For keys that exist in both T and U: Merges the content blocks using discriminated\n * union merging based on the \"type\" property. This allows combining different content\n * block types (e.g., text + image) for the same message type.\n * - For keys that exist only in T: Uses T's content definition as-is\n * - For keys that exist only in U: Uses U's content definition as-is\n *\n * @template T - The content definition from the first message structure\n * @template U - The content definition from the second message structure\n *\n * @example\n * ```ts\n * // T allows text content for human messages\n * type ContentA = {\n * human: ContentBlock.Text;\n * };\n *\n * // U allows image content for human messages and text for AI messages\n * type ContentB = {\n * human: ContentBlock.Multimodal.Image;\n * ai: ContentBlock.Text;\n * };\n *\n * // Merged result allows both text and images for human messages, text for AI\n * type Merged = $MergeContentDefinition<ContentA, ContentB>;\n * // Result: {\n * // human: ContentBlock.Text | ContentBlock.Multimodal.Image;\n * // ai: ContentBlock.Text;\n * // }\n * ```\n */\nexport type $MergeContentDefinition<T, U> = {\n [K in keyof T | keyof U as Extract<\n (K extends keyof T ? T[K] : never) | (K extends keyof U ? U[K] : never),\n ContentBlock\n > extends never\n ? never\n : K]: K extends keyof T\n ? K extends keyof U\n ? $MergeDiscriminatedUnion<\n Extract<T[K], ContentBlock>,\n Extract<U[K], ContentBlock>,\n \"type\"\n >\n : Extract<T[K], ContentBlock>\n : K extends keyof U\n ? Extract<U[K], ContentBlock>\n : never;\n};\n\n/**\n * Merges two message structures A and B into a combined structure.\n * This is a type utility that handles merging of tools, content blocks, and properties\n * from two message structures. The resulting type is usable as its own message structure.\n *\n * @example\n * ```ts\n * // Structure A allows text in human messages and has a confidence property on AI messages\n * interface StructureA extends MessageStructure {\n * content: {\n * human: ContentBlock.Text;\n * };\n * properties: {\n * ai: { confidence: number };\n * }\n * }\n *\n * // Structure B allows images in human messages and has a model property on AI messages\n * interface StructureB extends MessageStructure {\n * content: {\n * human: ContentBlock.Multimodal.Image;\n * };\n * properties: {\n * ai: { model: string };\n * }\n * }\n *\n * // Merged structure allows both text and images in human messages\n * // AI messages have both confidence and model properties\n * type Merged = $MergeMessageStructure<StructureA, StructureB>;\n * ```\n *\n * @template A - First message structure to merge\n * @template B - Second message structure to merge (takes precedence over A)\n */\nexport type $MergeMessageStructure<\n T extends MessageStructure,\n U extends MessageStructure,\n> = {\n outputVersion: $MergeOutputVersion<T[\"outputVersion\"], U[\"outputVersion\"]>;\n tools: $MergeObjects<T[\"tools\"], U[\"tools\"]>;\n content: $MergeContentDefinition<T[\"content\"], U[\"content\"]>;\n properties: $MergeObjects<T[\"properties\"], U[\"properties\"]>;\n};\n\n/**\n * Standard message structured used to define the most basic message structure that's\n * used throughout the library.\n *\n * This is also the message structure that's used when a message structure is not provided.\n */\nexport interface StandardMessageStructure extends MessageStructure {\n content: {\n /** Text content for AI messages */\n ai: ContentBlock.Text;\n /** Text content for human messages */\n human: ContentBlock.Text;\n /** Text content for system messages */\n system: ContentBlock.Text;\n /** Text content for tool messages */\n tool: ContentBlock.Text;\n };\n properties: {\n /** Properties specific to AI messages */\n ai: {\n /** Metadata about the AI model response */\n response_metadata: ResponseMetadata;\n /** Usage statistics for the AI response */\n usage_metadata: UsageMetadata;\n };\n human: {\n /** Metadata about the human message */\n response_metadata: Record<string, unknown>;\n };\n system: {\n /** Metadata about the system message */\n response_metadata: Record<string, unknown>;\n };\n tool: {\n /** Metadata about the tool message */\n response_metadata: Record<string, unknown>;\n };\n };\n}\n\n/**\n * Takes a message structure type T and normalizes it by merging it with the standard message structure.\n * If T is already a standard message structure, returns T unchanged.\n *\n * This ensures that any custom message structure includes all the standard message structure fields\n * by default while allowing overrides and extensions.\n *\n * @template T - The message structure type to normalize, must extend MessageStructure\n * @returns Either T if it's already a standard structure, or the merged result of T with standard structure\n */\nexport type $NormalizedMessageStructure<T extends MessageStructure> =\n T extends StandardMessageStructure\n ? T\n : $MergeMessageStructure<StandardMessageStructure, T>;\n\n/**\n * Infers the content blocks for a specific message type in a message structure.\n *\n * This utility type extracts the content block type that corresponds to a given message type\n * from the message structure's content definition.\n *\n * @template TStructure - The message structure to infer content from\n * @template TRole - The message role/type to get content for (e.g., \"ai\", \"human\", \"system\", \"tool\")\n * @returns The content block type for the specified type, or never if its not defined in the structure\n *\n * @example\n * ```ts\n * interface MyStructure extends MessageStructure {\n * content: {\n * human: ContentBlock.Text;\n * ai: ContentBlock.Text | ContentBlock.ToolCall;\n * };\n * }\n *\n * type HumanContent = $InferMessageContentBlocks<MyStructure, \"human\">;\n * // HumanContent = ContentBlock.Text\n *\n * type AIContent = $InferMessageContentBlocks<MyStructure, \"ai\">;\n * // AIContent = ContentBlock.Text | ContentBlock.ToolCall\n * ```\n */\nexport type $InferMessageContentBlocks<\n TStructure extends MessageStructure,\n TRole extends MessageType,\n> =\n $NormalizedMessageStructure<TStructure> extends infer S\n ? S extends MessageStructure\n ? S[\"content\"] extends infer C\n ? C extends Record<PropertyKey, ContentBlock>\n ? TRole extends keyof C\n ? [$MessageToolCallBlock<TStructure>] extends [never]\n ? C[TRole]\n : $MergeDiscriminatedUnion<\n NonNullable<C[TRole]>,\n $MessageToolCallBlock<TStructure>,\n \"type\"\n >\n : never\n : never\n : never\n : never\n : never;\n\n/**\n * Infers the content type for a specific message type from a message structure.\n *\n * This utility type determines the appropriate content type based on the message structure's\n * output version and the specified message type. The content type varies depending on the\n * output version (see {@link MessageOutputVersion})\n *\n * @template TStructure - The message structure to infer content from\n * @template TRole - The message role/type to get content for (e.g., \"ai\", \"human\", \"system\", \"tool\")\n * @returns The content type for the specified role based on the output version\n *\n * @example\n * ```ts\n * interface MyStructure extends MessageStructure {\n * outputVersion: \"v0\";\n * content: {\n * human: ContentBlock.Text;\n * ai: ContentBlock.Text | ContentBlock.ToolCall;\n * };\n * }\n *\n * type HumanContentV0 = $InferMessageContent<MyStructure, \"human\">;\n * // HumanContentV0 = string | Array<ContentBlock | ContentBlock.Text>\n *\n * interface MyStructureV1 extends MessageStructure {\n * outputVersion: \"v1\";\n * content: {\n * human: ContentBlock.Text;\n * ai: ContentBlock.Text | ContentBlock.Reasoning;\n * };\n * }\n *\n * type HumanContentV1 = $InferMessageContent<MyStructureV1, \"human\">;\n * // HumanContentV1 = ContentBlock.Text\n *\n * type AIContentV1 = $InferMessageContent<MyStructureV1, \"ai\">;\n * // AIContentV1 = ContentBlock.Text | ContentBlock.Reasoning\n * ```\n */\nexport type $InferMessageContent<\n TStructure extends MessageStructure,\n TRole extends MessageType,\n> = TRole extends \"tool\"\n ? // For tool messages, infer content from tool output types if available\n $InferToolOutputs<TStructure> extends infer TOutput\n ? [TOutput] extends [never]\n ? string | Array<ContentBlock | ContentBlock.Text>\n : [unknown] extends [TOutput]\n ? // Fallback to default when TOutput is unknown (no specific tools defined)\n string | Array<ContentBlock | ContentBlock.Text>\n : TOutput | string | Array<ContentBlock | ContentBlock.Text>\n : string | Array<ContentBlock | ContentBlock.Text>\n : TStructure[\"outputVersion\"] extends \"v1\"\n ? Array<$InferMessageContentBlocks<TStructure, TRole>>\n : string | Array<ContentBlock | ContentBlock.Text>;\n\n/**\n * Infers the properties for a specific message type from a message structure.\n *\n * This utility type extracts the properties object that corresponds to a given message type\n * from the message structure's properties definition, and excludes the reserved\n * \"content\" and \"type\" properties to avoid conflicts with the core message structure.\n *\n * If the specified type is not defined in the message structure's properties, it returns\n * a generic Record<string, unknown> type to allow for arbitrary properties.\n *\n * @template TStructure - The message structure to infer properties from\n * @template TRole - The message type/role to get properties for (e.g., \"ai\", \"human\", \"system\", \"tool\")\n * @returns The properties object type for the specified type, excluding \"content\" and \"type\"\n *\n * @example\n * ```ts\n * interface MyStructure extends MessageStructure {\n * properties: {\n * ai: {\n * response_metadata: { model: string };\n * usage_metadata: { tokens: number };\n * content: string; // This will be omitted\n * type: string; // This will be omitted\n * };\n * human: { metadata: Record<string, unknown> };\n * };\n * }\n *\n * type AIProperties = $InferMessageProperties<MyStructure, \"ai\">;\n * // AIProperties = { response_metadata: { model: string }; usage_metadata: { tokens: number } }\n *\n * type HumanProperties = $InferMessageProperties<MyStructure, \"human\">;\n * // HumanProperties = { metadata: Record<string, unknown> }\n *\n * type SystemProperties = $InferMessageProperties<MyStructure, \"system\">;\n * // SystemProperties = Record<string, unknown> (fallback for undefined role)\n * ```\n */\nexport type $InferMessageProperties<\n TStructure extends MessageStructure,\n TRole extends MessageType,\n> =\n $NormalizedMessageStructure<TStructure> extends infer S\n ? S extends MessageStructure\n ? S[\"properties\"] extends infer P | undefined\n ? P extends Record<PropertyKey, unknown>\n ? TRole extends keyof P\n ? Omit<P[TRole], \"content\" | \"type\">\n : Record<string, unknown>\n : Record<string, unknown>\n : Record<string, unknown>\n : never\n : never;\n\n/**\n * Infers the type of a specific property for a message type from a message structure.\n *\n * This utility type extracts the type of a single property by name from the properties\n * object that corresponds to a given message type. If the specified property key does\n * not exist in the type's properties, it returns `never`.\n *\n * @template TStructure - The message structure to infer the property from\n * @template TRole - The message type/role to get the property for (e.g., \"ai\", \"human\", \"system\", \"tool\")\n * @template K - The property key to extract the type for\n * @returns The type of the specified property, or `never` if the property doesn't exist\n *\n * @example\n * ```ts\n * interface MyStructure extends MessageStructure {\n * properties: {\n * ai: {\n * response_metadata: { model: string; temperature: number };\n * usage_metadata: { input_tokens: number; output_tokens: number };\n * };\n * human: { metadata: Record<string, unknown> };\n * };\n * }\n *\n * type ResponseMetadata = $InferMessageProperty<MyStructure, \"ai\", \"response_metadata\">;\n * // ResponseMetadata = { model: string; temperature: number }\n *\n * type UsageMetadata = $InferMessageProperty<MyStructure, \"ai\", \"usage_metadata\">;\n * // UsageMetadata = { input_tokens: number; output_tokens: number }\n *\n * type NonExistentProperty = $InferMessageProperty<MyStructure, \"ai\", \"nonExistent\">;\n * // NonExistentProperty = Record<string, unknown>\n *\n * type HumanMetadata = $InferMessageProperty<MyStructure, \"human\", \"metadata\">;\n * // HumanMetadata = Record<string, unknown>\n * ```\n */\nexport type $InferMessageProperty<\n TStructure extends MessageStructure,\n TRole extends MessageType,\n K extends string,\n> = K extends keyof $InferMessageProperties<TStructure, TRole>\n ? $InferMessageProperties<TStructure, TRole>[K]\n : never;\n\n/**\n * Infers the response metadata type for a specific message type from a message structure.\n *\n * This utility type extracts the `response_metadata` property type for a given message type.\n *\n * @template TStructure - The message structure to infer the response metadata from\n * @template TRole - The message type/role to get the response metadata for (e.g., \"ai\", \"human\", \"system\", \"tool\")\n * @returns The type of the response_metadata property, or `Record<string, unknown>` as fallback\n *\n * @example\n * ```ts\n * interface MyStructure extends MessageStructure {\n * properties: {\n * ai: {\n * response_metadata: { model: string; temperature: number; tokens: number };\n * };\n * human: { metadata: Record<string, unknown> };\n * };\n * }\n *\n * type AIResponseMetadata = $InferResponseMetadata<MyStructure, \"ai\">;\n * // AIResponseMetadata = { model: string; temperature: number; tokens: number }\n *\n * type HumanResponseMetadata = $InferResponseMetadata<MyStructure, \"human\">;\n * // HumanResponseMetadata = Record<string, unknown> (fallback since not defined)\n * ```\n */\nexport type $InferResponseMetadata<\n TStructure extends MessageStructure,\n TRole extends MessageType,\n> =\n $InferMessageProperty<TStructure, TRole, \"response_metadata\"> extends infer P\n ? [P] extends [never]\n ? Record<string, unknown>\n : P\n : never;\n\n/**\n * Represents a message object that organizes context for an LLM.\n *\n * @example\n * ```ts\n * // Basic message with text content\n * const message: Message = {\n * id: \"msg-123\",\n * name: \"user\",\n * type: \"human\",\n * content: [{ type: \"text\", text: \"Hello!\" }]\n * };\n *\n * // Basic ai message interface extension\n * interface MyMessage extends Message<StandardMessageStructure, \"ai\"> {\n * // Additional AI-specific properties can be added here\n * }\n *`\n * // Custom message structure\n * interface CustomStructure extends MessageStructure {\n * content: {\n * ai: ContentBlock.Text | ContentBlock.ToolCall<\"search\", { query: string }>;\n * human: ContentBlock.Text | ContentBlock.Multimodal.Image;\n * };\n * }\n *\n * // Create a message with custom structure\n * const message: Message<CustomStructure> = {\n * id: \"msg-123\",\n * name: \"user\",\n * type: \"ai\",\n * content: [\n * { type: \"text\", text: \"Hello!\" },\n * {\n * type: \"tool_call\",\n * name: \"search\",\n * args: { query: \"What is the capital of France?\" }\n * }\n * ]\n * };\n * ```\n */\nexport interface Message<\n TStructure extends MessageStructure = StandardMessageStructure,\n TRole extends MessageType = MessageType,\n> {\n /** The message type/role */\n readonly type: TRole;\n /** Unique identifier for this message */\n id?: string;\n /**\n * An optional name for the message participant.\n *\n * This property is primarily used to:\n *\n * 1. **Identify agent roles in multi-agent systems**: When multiple agents\n * collaborate, setting `name` helps distinguish which agent produced a\n * message, preventing confusion about who said what.\n *\n * 2. **Pass participant names to model providers**: Some providers (notably\n * OpenAI, e.g. see {@link https://platform.openai.com/docs/api-reference/chat/create | OpenAI Chat Completions API})\n * use this field to differentiate between participants with the\n * same role. For example, when using OpenAI's Chat Completions API, the\n * `name` is included in the message payload sent to the model.\n *\n * @example\n * ```typescript\n * // Setting name on an AIMessage to identify the agent\n * const message = new AIMessage({\n * content: \"I'll handle the calendar scheduling.\",\n * name: \"calendar_agent\"\n * });\n *\n * // In a multi-agent system, this helps track message origins\n * const researcherMessage = new AIMessage({\n * content: \"Here are the findings...\",\n * name: \"researcher\"\n * });\n * const writerMessage = new AIMessage({\n * content: \"I've drafted the report.\",\n * name: \"writer\"\n * });\n * ```\n */\n name?: string;\n /** Array of content blocks that make up the message content */\n content: $InferMessageContent<TStructure, TRole>;\n /** Metadata about the message */\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n}\n\n/**\n * Type guard to check if a value is a valid Message object.\n *\n * @param message - The value to check\n * @returns true if the value is a valid Message object, false otherwise\n */\nexport function isMessage(message: unknown): message is Message {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"type\" in message &&\n \"content\" in message &&\n (typeof message.content === \"string\" || Array.isArray(message.content))\n );\n}\n"],"mappings":";;;;;;;AAk1BA,SAAgB,UAAUA,SAAsC;AAC9D,QACE,OAAO,YAAY,YACnB,YAAY,QACZ,UAAU,WACV,aAAa,YACZ,OAAO,QAAQ,YAAY,YAAY,MAAM,QAAQ,QAAQ,QAAQ;AAEzE"}
|
|
1
|
+
{"version":3,"file":"message.js","names":["message: unknown"],"sources":["../../src/messages/message.ts"],"sourcesContent":["import type { ContentBlock } from \"./content/index.js\";\nimport type { ResponseMetadata, UsageMetadata } from \"./metadata.js\";\nimport type { $MergeDiscriminatedUnion, $MergeObjects } from \"./utils.js\";\n\n/**\n * Represents the possible types of messages in the system.\n * Includes standard message types (\"ai\", \"human\", \"tool\", \"system\")\n * and allows for custom string types that are non-null.\n *\n * @example\n * ```ts\n * // Standard message types\n * const messageType1: MessageType = \"ai\";\n * const messageType2: MessageType = \"human\";\n *\n * // Custom message type\n * const messageType3: MessageType = \"custom_type\";\n * ```\n */\nexport type MessageType =\n | \"ai\"\n | \"human\"\n | \"tool\"\n | \"system\"\n | (string & NonNullable<unknown>);\n\n/**\n * Represents the output version format for message content.\n *\n * This type determines how the content field is structured in a message:\n * - \"v0\": Content is represented as a simple string or array of content blocks\n * - provides backward compatibility with simpler content representations\n * - \"v1\": Content follows the structured ContentBlock format with typed discriminated unions\n * - enables full type safety and structured content block handling\n *\n * @example\n * ```ts\n * // v0 format - simple content representation\n * const v0Message: Message<{ outputVersion: \"v0\", content: ... }> = {\n * type: \"human\",\n * content: \"Hello world\" // string | Array<ContentBlock | ContentBlock.Text>\n * };\n *\n * // v1 format - structured content blocks\n * const v1Message: Message<{ outputVersion: \"v1\", content: ... }> = {\n * type: \"human\",\n * content: [\n * { type: \"text\", text: \"Hello world\" },\n * { type: \"image\", image_url: \"...\" }\n * ] // Array<ContentBlock | ...> (determined by the structure)\n * };\n * ```\n */\nexport type MessageOutputVersion = \"v0\" | \"v1\";\n\n/**\n * Represents the input and output types of a tool that can be used in messages.\n *\n * @template TInput - The type of input the tool accepts.\n * @template TOutput - The type of output the tool produces.\n *\n * @example\n * ```ts\n * // Tool that takes a string input and returns a number\n * interface StringToNumberTool extends MessageToolDefinition<string, number> {\n * input: string;\n * output: number;\n * }\n * ```\n */\nexport interface MessageToolDefinition<TInput = unknown, TOutput = unknown> {\n input: TInput;\n output: TOutput;\n}\n\n/**\n * Represents a structured set of tools by mapping tool names to definitions\n * that can be used in messages.\n *\n * @example\n * ```ts\n * interface MyToolSet extends MessageToolSet {\n * calculator: MessageToolDefinition<\n * { operation: string; numbers: number[] },\n * number\n * >;\n * translator: MessageToolDefinition<\n * { text: string; targetLanguage: string },\n * string\n * >;\n * }\n * ```\n */\nexport interface MessageToolSet {\n [key: string]: MessageToolDefinition;\n}\n\n/**\n * Represents a tool call block within a message structure by mapping tool names to their\n * corresponding tool call formats, including the input arguments and an optional identifier.\n *\n * @template TStructure - A message structure type that may contain tool definitions\n *\n * @example\n * ```ts\n * // Given a message structure with a calculator tool:\n * interface MyStructure extends MessageStructure {\n * tools: {\n * calculator: MessageToolDefinition<{ operation: string, numbers: number[] }, number>\n * }\n * }\n *\n * // The tool call block would be:\n * type CalcToolCall = $MessageToolCallBlock<MyStructure>;\n * // Resolves to:\n * // {\n * // type: \"tool_call\";\n * // name: \"calculator\";\n * // args: { operation: string, numbers: number[] };\n * // id?: string;\n * // }\n * ```\n */\nexport type $MessageToolCallBlock<TStructure extends MessageStructure> =\n TStructure[\"tools\"] extends MessageToolSet\n ? {\n [K in keyof TStructure[\"tools\"]]: K extends string\n ? TStructure[\"tools\"][K] extends MessageToolDefinition\n ? ContentBlock.Tools.ToolCall<K, TStructure[\"tools\"][K][\"input\"]>\n : never\n : never;\n }[keyof TStructure[\"tools\"]]\n : never;\n\n/**\n * Helper type to infer a union of ToolCall types from the tools defined in a MessageStructure.\n * This is used to type the `tool_calls` array in AIMessage based on the available tools.\n *\n * @template TStructure - A message structure type that may contain tool definitions\n *\n * @example\n * ```ts\n * // Given a message structure with tools:\n * interface MyStructure extends MessageStructure {\n * tools: {\n * calculator: MessageToolDefinition<{ a: number, b: number }, number>;\n * search: MessageToolDefinition<{ query: string }, string[]>;\n * }\n * }\n *\n * // The inferred tool calls would be:\n * type ToolCalls = $InferToolCalls<MyStructure>;\n * // Resolves to:\n * // | { type?: \"tool_call\"; id?: string; name: \"calculator\"; args: { a: number, b: number } }\n * // | { type?: \"tool_call\"; id?: string; name: \"search\"; args: { query: string } }\n * ```\n */\nexport type $InferToolCalls<TStructure extends MessageStructure> =\n NonNullable<TStructure[\"tools\"]> extends MessageToolSet\n ? NonNullable<TStructure[\"tools\"]> extends infer TTools extends\n MessageToolSet\n ? {\n [K in keyof TTools]: K extends string\n ? TTools[K] extends MessageToolDefinition\n ? {\n readonly type?: \"tool_call\";\n id?: string;\n name: K;\n // Fallback to Record<string, any> when input is unknown\n args: [unknown] extends [TTools[K][\"input\"]]\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Record<string, any>\n : TTools[K][\"input\"];\n }\n : never\n : never;\n }[keyof TTools]\n : never\n : {\n readonly type?: \"tool_call\";\n id?: string;\n name: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: Record<string, any>;\n };\n\n/**\n * Helper type to infer a union of tool output types from the tools defined in a MessageStructure.\n * This is used to type the `content` of ToolMessage based on the available tool outputs.\n *\n * @template TStructure - A message structure type that may contain tool definitions\n *\n * @example\n * ```ts\n * // Given a message structure with tools:\n * interface MyStructure extends MessageStructure {\n * tools: {\n * calculator: MessageToolDefinition<{ a: number, b: number }, number>;\n * search: MessageToolDefinition<{ query: string }, string[]>;\n * }\n * }\n *\n * // The inferred tool outputs would be:\n * type ToolOutputs = $InferToolOutputs<MyStructure>;\n * // Resolves to: number | string[]\n * ```\n */\nexport type $InferToolOutputs<TStructure extends MessageStructure> =\n NonNullable<TStructure[\"tools\"]> extends MessageToolSet\n ? NonNullable<TStructure[\"tools\"]> extends infer TTools extends\n MessageToolSet\n ? {\n [K in keyof TTools]: TTools[K] extends MessageToolDefinition\n ? TTools[K][\"output\"]\n : never;\n }[keyof TTools]\n : unknown\n : unknown;\n\n/**\n * Core interface that defines the structure of messages.\n *\n * @example\n * ```ts\n * // Basic message structure with just content blocks\n * interface SimpleMessageStructure extends MessageStructure {\n * content: {\n * human: ContentBlock.Text;\n * // allows for text + reasoning blocks in ai messages\n * ai: ContentBlock.Text | ContentBlock.Reasoning;\n * }\n * }\n *\n * // Message structure with tools and properties\n * interface AdvancedMessageStructure extends MessageStructure {\n * tools: {\n * calculator: MessageToolDefinition<\n * { operation: string; numbers: number[] },\n * number\n * >;\n * };\n * content: {\n * // allows for text + image blocks in human messages\n * human: ContentBlock.Text | ContentBlock.Multimodal.Image;\n * // only allows for text blocks in ai messages\n * ai: ContentBlock.Text;\n * };\n * properties: {\n * // pins properties to ai messages\n * ai: {\n * response_metadata: {\n * confidence: number;\n * model: string;\n * };\n * };\n * }\n * }\n *\n * // Using with $MergeMessageStructure to combine structures\n * // The resulting type when passed into BaseMessage will have a calculator tool,\n * // allow for text + image blocks in human messages,\n * // and text + reasoning blocks + additional arbitrary properties in ai messages.\n * type CombinedStructure = $MergeMessageStructure<\n * SimpleMessageStructure,\n * AdvancedMessageStructure\n * >;\n *\n * // Using in a Message object\n * const message: Message<CombinedStructure> = {\n * id: \"msg-123\",\n * type: \"human\",\n * content: [\n * { type: \"text\", text: \"Hello!\" }\n * { type: \"image\", mimeType: \"image/jpeg\", url: \"https://example.com/image.jpg\" }\n * // this block will throw an error because it's not defined in the structure\n * { type: \"reasoning\", reasoning: \"The answer is 42\" }\n * ]\n * };\n * ```\n */\nexport interface MessageStructure<\n TTools extends MessageToolSet = MessageToolSet,\n> {\n /**\n * Optional output version for the message structure.\n * If not provided, defaults to \"v0\".\n */\n readonly outputVersion?: MessageOutputVersion;\n /**\n * Optional set of tool definitions that can be used in messages.\n * Each tool is defined with input/output types and can be referenced in tool messages.\n */\n readonly tools?: TTools;\n /**\n * Optional mapping of message types to their allowed content blocks.\n * Each message type can specify what content block types it supports (text, images, etc).\n */\n readonly content?: Partial<{\n [key in MessageType]: ContentBlock;\n }>;\n /**\n * Optional mapping of message types to arbitrary property objects.\n * Allows attaching custom metadata or other information to specific message types.\n */\n readonly properties?: Partial<{\n [key in MessageType]: Record<string, unknown>;\n }>;\n}\n\n/**\n * Normalizes an arbitrary type to a message output version or undefined.\n * Accepts unknown and narrows to a valid MessageOutputVersion if present.\n */\ntype $NormalizeMessageOutputVersion<T> =\n | Extract<T, MessageOutputVersion>\n | undefined;\n\n/**\n * Merges two output version types from message structures.\n *\n * This utility type determines the resulting output version when combining two message structures.\n * The merge logic follows these rules:\n *\n * - If both T and U are undefined, defaults to \"v0\" for backwards compatibility\n * - If T is undefined but U is defined, uses U's version\n * - If U is undefined but T is defined, uses T's version\n * - If both T and U are defined, U takes precedence (later structure wins)\n *\n * @template T - The output version from the first message structure\n * @template U - The output version from the second message structure\n *\n * @example\n * ```ts\n * // Both undefined - defaults to \"v0\"\n * type Result1 = $MergeOutputVersion<undefined, undefined>; // \"v0\"\n *\n * // One defined - uses the defined version\n * type Result2 = $MergeOutputVersion<undefined, \"v1\">; // \"v1\"\n * type Result3 = $MergeOutputVersion<\"v0\", undefined>; // \"v0\"\n *\n * // Both defined - second takes precedence\n * type Result4 = $MergeOutputVersion<\"v0\", \"v1\">; // \"v1\"\n * ```\n */\nexport type $MergeOutputVersion<T, U> =\n $NormalizeMessageOutputVersion<T> extends infer TV\n ? $NormalizeMessageOutputVersion<U> extends infer UV\n ? [TV, UV] extends [undefined, undefined]\n ? \"v0\"\n : [TV] extends [undefined]\n ? Exclude<UV, undefined>\n : [UV] extends [undefined]\n ? Exclude<TV, undefined>\n : UV\n : never\n : never;\n\n/**\n * Merges two content definition objects from message structures.\n *\n * This utility type combines content definitions from two message structures, handling\n * the merging of content block types for each message type. The merge logic follows\n * these rules:\n *\n * - For keys that exist in both T and U: Merges the content blocks using discriminated\n * union merging based on the \"type\" property. This allows combining different content\n * block types (e.g., text + image) for the same message type.\n * - For keys that exist only in T: Uses T's content definition as-is\n * - For keys that exist only in U: Uses U's content definition as-is\n *\n * @template T - The content definition from the first message structure\n * @template U - The content definition from the second message structure\n *\n * @example\n * ```ts\n * // T allows text content for human messages\n * type ContentA = {\n * human: ContentBlock.Text;\n * };\n *\n * // U allows image content for human messages and text for AI messages\n * type ContentB = {\n * human: ContentBlock.Multimodal.Image;\n * ai: ContentBlock.Text;\n * };\n *\n * // Merged result allows both text and images for human messages, text for AI\n * type Merged = $MergeContentDefinition<ContentA, ContentB>;\n * // Result: {\n * // human: ContentBlock.Text | ContentBlock.Multimodal.Image;\n * // ai: ContentBlock.Text;\n * // }\n * ```\n */\nexport type $MergeContentDefinition<T, U> = {\n [K in keyof T | keyof U as Extract<\n (K extends keyof T ? T[K] : never) | (K extends keyof U ? U[K] : never),\n ContentBlock\n > extends never\n ? never\n : K]: K extends keyof T\n ? K extends keyof U\n ? $MergeDiscriminatedUnion<\n Extract<T[K], ContentBlock>,\n Extract<U[K], ContentBlock>,\n \"type\"\n >\n : Extract<T[K], ContentBlock>\n : K extends keyof U\n ? Extract<U[K], ContentBlock>\n : never;\n};\n\n/**\n * Merges two message structures A and B into a combined structure.\n * This is a type utility that handles merging of tools, content blocks, and properties\n * from two message structures. The resulting type is usable as its own message structure.\n *\n * @example\n * ```ts\n * // Structure A allows text in human messages and has a confidence property on AI messages\n * interface StructureA extends MessageStructure {\n * content: {\n * human: ContentBlock.Text;\n * };\n * properties: {\n * ai: { confidence: number };\n * }\n * }\n *\n * // Structure B allows images in human messages and has a model property on AI messages\n * interface StructureB extends MessageStructure {\n * content: {\n * human: ContentBlock.Multimodal.Image;\n * };\n * properties: {\n * ai: { model: string };\n * }\n * }\n *\n * // Merged structure allows both text and images in human messages\n * // AI messages have both confidence and model properties\n * type Merged = $MergeMessageStructure<StructureA, StructureB>;\n * ```\n *\n * @template A - First message structure to merge\n * @template B - Second message structure to merge (takes precedence over A)\n */\nexport type $MergeMessageStructure<\n T extends MessageStructure,\n U extends MessageStructure,\n> = {\n outputVersion: $MergeOutputVersion<T[\"outputVersion\"], U[\"outputVersion\"]>;\n tools: $MergeObjects<T[\"tools\"], U[\"tools\"]>;\n content: $MergeContentDefinition<T[\"content\"], U[\"content\"]>;\n properties: $MergeObjects<T[\"properties\"], U[\"properties\"]>;\n};\n\n/**\n * Standard message structured used to define the most basic message structure that's\n * used throughout the library.\n *\n * This is also the message structure that's used when a message structure is not provided.\n */\nexport interface StandardMessageStructure extends MessageStructure {\n content: {\n /** Text content for AI messages */\n ai: ContentBlock.Text;\n /** Text content for human messages */\n human: ContentBlock.Text;\n /** Text content for system messages */\n system: ContentBlock.Text;\n /** Text content for tool messages */\n tool: ContentBlock.Text;\n };\n properties: {\n /** Properties specific to AI messages */\n ai: {\n /** Metadata about the AI model response */\n response_metadata: ResponseMetadata;\n /** Usage statistics for the AI response */\n usage_metadata: UsageMetadata;\n };\n human: {\n /** Metadata about the human message */\n response_metadata: Record<string, unknown>;\n };\n system: {\n /** Metadata about the system message */\n response_metadata: Record<string, unknown>;\n };\n tool: {\n /** Metadata about the tool message */\n response_metadata: Record<string, unknown>;\n };\n };\n}\n\n/**\n * Takes a message structure type T and normalizes it by merging it with the standard message structure.\n * If T is already a standard message structure, returns T unchanged.\n *\n * This ensures that any custom message structure includes all the standard message structure fields\n * by default while allowing overrides and extensions.\n *\n * @template T - The message structure type to normalize, must extend MessageStructure\n * @returns Either T if it's already a standard structure, or the merged result of T with standard structure\n */\nexport type $NormalizedMessageStructure<T extends MessageStructure> =\n T extends StandardMessageStructure\n ? T\n : $MergeMessageStructure<StandardMessageStructure, T>;\n\n/**\n * Infers the content blocks for a specific message type in a message structure.\n *\n * This utility type extracts the content block type that corresponds to a given message type\n * from the message structure's content definition.\n *\n * @template TStructure - The message structure to infer content from\n * @template TRole - The message role/type to get content for (e.g., \"ai\", \"human\", \"system\", \"tool\")\n * @returns The content block type for the specified type, or never if its not defined in the structure\n *\n * @example\n * ```ts\n * interface MyStructure extends MessageStructure {\n * content: {\n * human: ContentBlock.Text;\n * ai: ContentBlock.Text | ContentBlock.ToolCall;\n * };\n * }\n *\n * type HumanContent = $InferMessageContentBlocks<MyStructure, \"human\">;\n * // HumanContent = ContentBlock.Text\n *\n * type AIContent = $InferMessageContentBlocks<MyStructure, \"ai\">;\n * // AIContent = ContentBlock.Text | ContentBlock.ToolCall\n * ```\n */\nexport type $InferMessageContentBlocks<\n TStructure extends MessageStructure,\n TRole extends MessageType,\n> =\n $NormalizedMessageStructure<TStructure> extends infer S\n ? S extends MessageStructure\n ? S[\"content\"] extends infer C\n ? C extends Record<PropertyKey, ContentBlock>\n ? TRole extends keyof C\n ? [$MessageToolCallBlock<TStructure>] extends [never]\n ? C[TRole]\n : $MergeDiscriminatedUnion<\n NonNullable<C[TRole]>,\n $MessageToolCallBlock<TStructure>,\n \"type\"\n >\n : never\n : never\n : never\n : never\n : never;\n\n/**\n * Infers the content type for a specific message type from a message structure.\n *\n * This utility type determines the appropriate content type based on the message structure's\n * output version and the specified message type. The content type varies depending on the\n * output version (see {@link MessageOutputVersion})\n *\n * @template TStructure - The message structure to infer content from\n * @template TRole - The message role/type to get content for (e.g., \"ai\", \"human\", \"system\", \"tool\")\n * @returns The content type for the specified role based on the output version\n *\n * @example\n * ```ts\n * interface MyStructure extends MessageStructure {\n * outputVersion: \"v0\";\n * content: {\n * human: ContentBlock.Text;\n * ai: ContentBlock.Text | ContentBlock.ToolCall;\n * };\n * }\n *\n * type HumanContentV0 = $InferMessageContent<MyStructure, \"human\">;\n * // HumanContentV0 = string | Array<ContentBlock | ContentBlock.Text>\n *\n * interface MyStructureV1 extends MessageStructure {\n * outputVersion: \"v1\";\n * content: {\n * human: ContentBlock.Text;\n * ai: ContentBlock.Text | ContentBlock.Reasoning;\n * };\n * }\n *\n * type HumanContentV1 = $InferMessageContent<MyStructureV1, \"human\">;\n * // HumanContentV1 = ContentBlock.Text\n *\n * type AIContentV1 = $InferMessageContent<MyStructureV1, \"ai\">;\n * // AIContentV1 = ContentBlock.Text | ContentBlock.Reasoning\n * ```\n */\nexport type $InferMessageContent<\n TStructure extends MessageStructure,\n TRole extends MessageType,\n> = TRole extends \"tool\"\n ? // For tool messages, infer content from tool output types if available\n $InferToolOutputs<TStructure> extends infer TOutput\n ? [TOutput] extends [never]\n ? string | Array<ContentBlock | ContentBlock.Text>\n : [unknown] extends [TOutput]\n ? // Fallback to default when TOutput is unknown (no specific tools defined)\n string | Array<ContentBlock | ContentBlock.Text>\n : TOutput | string | Array<ContentBlock | ContentBlock.Text>\n : string | Array<ContentBlock | ContentBlock.Text>\n : TStructure[\"outputVersion\"] extends \"v1\"\n ? Array<$InferMessageContentBlocks<TStructure, TRole>>\n : string | Array<ContentBlock | ContentBlock.Text>;\n\n/**\n * Infers the properties for a specific message type from a message structure.\n *\n * This utility type extracts the properties object that corresponds to a given message type\n * from the message structure's properties definition, and excludes the reserved\n * \"content\" and \"type\" properties to avoid conflicts with the core message structure.\n *\n * If the specified type is not defined in the message structure's properties, it returns\n * a generic Record<string, unknown> type to allow for arbitrary properties.\n *\n * @template TStructure - The message structure to infer properties from\n * @template TRole - The message type/role to get properties for (e.g., \"ai\", \"human\", \"system\", \"tool\")\n * @returns The properties object type for the specified type, excluding \"content\" and \"type\"\n *\n * @example\n * ```ts\n * interface MyStructure extends MessageStructure {\n * properties: {\n * ai: {\n * response_metadata: { model: string };\n * usage_metadata: { tokens: number };\n * content: string; // This will be omitted\n * type: string; // This will be omitted\n * };\n * human: { metadata: Record<string, unknown> };\n * };\n * }\n *\n * type AIProperties = $InferMessageProperties<MyStructure, \"ai\">;\n * // AIProperties = { response_metadata: { model: string }; usage_metadata: { tokens: number } }\n *\n * type HumanProperties = $InferMessageProperties<MyStructure, \"human\">;\n * // HumanProperties = { metadata: Record<string, unknown> }\n *\n * type SystemProperties = $InferMessageProperties<MyStructure, \"system\">;\n * // SystemProperties = Record<string, unknown> (fallback for undefined role)\n * ```\n */\nexport type $InferMessageProperties<\n TStructure extends MessageStructure,\n TRole extends MessageType,\n> =\n $NormalizedMessageStructure<TStructure> extends infer S\n ? S extends MessageStructure\n ? S[\"properties\"] extends infer P | undefined\n ? P extends Record<PropertyKey, unknown>\n ? TRole extends keyof P\n ? Omit<P[TRole], \"content\" | \"type\">\n : Record<string, unknown>\n : Record<string, unknown>\n : Record<string, unknown>\n : never\n : never;\n\n/**\n * Infers the type of a specific property for a message type from a message structure.\n *\n * This utility type extracts the type of a single property by name from the properties\n * object that corresponds to a given message type. If the specified property key does\n * not exist in the type's properties, it returns `never`.\n *\n * @template TStructure - The message structure to infer the property from\n * @template TRole - The message type/role to get the property for (e.g., \"ai\", \"human\", \"system\", \"tool\")\n * @template K - The property key to extract the type for\n * @returns The type of the specified property, or `never` if the property doesn't exist\n *\n * @example\n * ```ts\n * interface MyStructure extends MessageStructure {\n * properties: {\n * ai: {\n * response_metadata: { model: string; temperature: number };\n * usage_metadata: { input_tokens: number; output_tokens: number };\n * };\n * human: { metadata: Record<string, unknown> };\n * };\n * }\n *\n * type ResponseMetadata = $InferMessageProperty<MyStructure, \"ai\", \"response_metadata\">;\n * // ResponseMetadata = { model: string; temperature: number }\n *\n * type UsageMetadata = $InferMessageProperty<MyStructure, \"ai\", \"usage_metadata\">;\n * // UsageMetadata = { input_tokens: number; output_tokens: number }\n *\n * type NonExistentProperty = $InferMessageProperty<MyStructure, \"ai\", \"nonExistent\">;\n * // NonExistentProperty = Record<string, unknown>\n *\n * type HumanMetadata = $InferMessageProperty<MyStructure, \"human\", \"metadata\">;\n * // HumanMetadata = Record<string, unknown>\n * ```\n */\nexport type $InferMessageProperty<\n TStructure extends MessageStructure,\n TRole extends MessageType,\n K extends string,\n> = K extends keyof $InferMessageProperties<TStructure, TRole>\n ? $InferMessageProperties<TStructure, TRole>[K]\n : never;\n\n/**\n * Infers the response metadata type for a specific message type from a message structure.\n *\n * This utility type extracts the `response_metadata` property type for a given message type.\n *\n * @template TStructure - The message structure to infer the response metadata from\n * @template TRole - The message type/role to get the response metadata for (e.g., \"ai\", \"human\", \"system\", \"tool\")\n * @returns The type of the response_metadata property, or `Record<string, unknown>` as fallback\n *\n * @example\n * ```ts\n * interface MyStructure extends MessageStructure {\n * properties: {\n * ai: {\n * response_metadata: { model: string; temperature: number; tokens: number };\n * };\n * human: { metadata: Record<string, unknown> };\n * };\n * }\n *\n * type AIResponseMetadata = $InferResponseMetadata<MyStructure, \"ai\">;\n * // AIResponseMetadata = { model: string; temperature: number; tokens: number }\n *\n * type HumanResponseMetadata = $InferResponseMetadata<MyStructure, \"human\">;\n * // HumanResponseMetadata = Record<string, unknown> (fallback since not defined)\n * ```\n */\nexport type $InferResponseMetadata<\n TStructure extends MessageStructure,\n TRole extends MessageType,\n> =\n $InferMessageProperty<TStructure, TRole, \"response_metadata\"> extends infer P\n ? [P] extends [never]\n ? Record<string, unknown>\n : P\n : never;\n\n/**\n * Represents a message object that organizes context for an LLM.\n *\n * @example\n * ```ts\n * // Basic message with text content\n * const message: Message = {\n * id: \"msg-123\",\n * name: \"user\",\n * type: \"human\",\n * content: [{ type: \"text\", text: \"Hello!\" }]\n * };\n *\n * // Basic ai message interface extension\n * interface MyMessage extends Message<StandardMessageStructure, \"ai\"> {\n * // Additional AI-specific properties can be added here\n * }\n *`\n * // Custom message structure\n * interface CustomStructure extends MessageStructure {\n * content: {\n * ai: ContentBlock.Text | ContentBlock.ToolCall<\"search\", { query: string }>;\n * human: ContentBlock.Text | ContentBlock.Multimodal.Image;\n * };\n * }\n *\n * // Create a message with custom structure\n * const message: Message<CustomStructure> = {\n * id: \"msg-123\",\n * name: \"user\",\n * type: \"ai\",\n * content: [\n * { type: \"text\", text: \"Hello!\" },\n * {\n * type: \"tool_call\",\n * name: \"search\",\n * args: { query: \"What is the capital of France?\" }\n * }\n * ]\n * };\n * ```\n */\nexport interface Message<\n TStructure extends MessageStructure = StandardMessageStructure,\n TRole extends MessageType = MessageType,\n> {\n /** The message type/role */\n readonly type: TRole;\n /** Unique identifier for this message */\n id?: string;\n /**\n * An optional name for the message participant.\n *\n * This property is primarily used to:\n *\n * 1. **Identify agent roles in multi-agent systems**: When multiple agents\n * collaborate, setting `name` helps distinguish which agent produced a\n * message, preventing confusion about who said what.\n *\n * 2. **Pass participant names to model providers**: Some providers (notably\n * OpenAI, e.g. see {@link https://platform.openai.com/docs/api-reference/chat/create | OpenAI Chat Completions API})\n * use this field to differentiate between participants with the\n * same role. For example, when using OpenAI's Chat Completions API, the\n * `name` is included in the message payload sent to the model.\n *\n * @example\n * ```typescript\n * // Setting name on an AIMessage to identify the agent\n * const message = new AIMessage({\n * content: \"I'll handle the calendar scheduling.\",\n * name: \"calendar_agent\"\n * });\n *\n * // In a multi-agent system, this helps track message origins\n * const researcherMessage = new AIMessage({\n * content: \"Here are the findings...\",\n * name: \"researcher\"\n * });\n * const writerMessage = new AIMessage({\n * content: \"I've drafted the report.\",\n * name: \"writer\"\n * });\n * ```\n */\n name?: string;\n /** Array of content blocks that make up the message content */\n content: $InferMessageContent<TStructure, TRole>;\n /** Metadata about the message */\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n}\n\n/**\n * Type guard to check if a value is a valid Message object.\n *\n * @param message - The value to check\n * @returns true if the value is a valid Message object, false otherwise\n */\nexport function isMessage(message: unknown): message is Message {\n return (\n typeof message === \"object\" &&\n message !== null &&\n \"type\" in message &&\n \"content\" in message &&\n (typeof message.content === \"string\" || Array.isArray(message.content))\n );\n}\n"],"mappings":";;;;;;;AAk1BA,SAAgB,UAAUA,SAAsC;AAC9D,QACE,OAAO,YAAY,YACnB,YAAY,QACZ,UAAU,WACV,aAAa,YACZ,OAAO,QAAQ,YAAY,YAAY,MAAM,QAAQ,QAAQ,QAAQ;AAEzE"}
|
|
@@ -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;CACnD,OAAO,UAAU;AACf,SAAO;CACR;CAED,eAAe;EAAC;EAAa;EAAkB;CAAa;CAE5D,SAAS;AACP,SAAO,KAAK,sBAAsB;CACnC;CAED,YAAmBC,QAAW;EAC5B,MAAM,OAAO;EADI;CAElB;;;;;;CAOD,OAAO,cAAwCA,QAAW;AACxD,SAAO,IAAI,KAAK;CACjB;;;;;;;CAQD,OAAO,yBACLC,SACA;EACA,MAAM,YAAYC,SAAE,OAClB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,IACtB,CAAC,CAAC,MAAM,YAAY,KAClB,CAAC,MAAMA,SAAE,QAAQ,CAAC,SAAS,YAAY,AAAC,EAC3C,CACF,CACF;AAED,SAAO,IAAI,KAAK;CACjB;;;;;;;CAQD,wBAAgC;AAC9B,SAAO,CAAC;;;;;;;;;;;;AAYZ,EAAE,KAAK,UAAUC,uCAAa,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,MAAMC,8BAAkB,KAAK,QAAQ,KAAK,MAAM,YAAY,CAAC;EACrE,SAAQ,GAAG;AACV,SAAM,IAAIC,mCACR,CAAC,wBAAwB,EAAE,KAAK,UAAU,EAAE,GAAG,EAC/C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AED,SAAO,KAAK,gBAAgB,YAAY;CACzC;CAED,wBAAgC;AAC9B,SAAO,KAAK,sBAAsB,uBAAuB;CAC1D;AACF"}
|
|
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 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,cAEUA,8BAA2C;CACnD,OAAO,UAAU;AACf,SAAO;CACR;CAED,eAAe;EAAC;EAAa;EAAkB;CAAa;CAE5D,SAAS;AACP,SAAO,KAAK,sBAAsB;CACnC;CAED,YAAmBC,QAAW;EAC5B,MAAM,OAAO;EADI;CAElB;;;;;;CAOD,OAAO,cAAwCA,QAAW;AACxD,SAAO,IAAI,KAAK;CACjB;;;;;;;CAQD,OAAO,yBACLC,SACA;EACA,MAAM,YAAYC,SAAE,OAClB,OAAO,YACL,OAAO,QAAQ,QAAQ,CAAC,IACtB,CAAC,CAAC,MAAM,YAAY,KAClB,CAAC,MAAMA,SAAE,QAAQ,CAAC,SAAS,YAAY,AAAC,EAC3C,CACF,CACF;AAED,SAAO,IAAI,KAAK;CACjB;;;;;;;CAQD,wBAAgC;AAC9B,SAAO,CAAC;;;;;;;;;;;;AAYZ,EAAE,KAAK,UAAUC,uCAAa,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,MAAMC,8BAAkB,KAAK,QAAQ,KAAK,MAAM,YAAY,CAAC;EACrE,SAAQ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AACV,SAAM,IAAIE,mCACR,CAAC,wBAAwB,EAAE,KAAK,UAAU,EAAE,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":"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,k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KAAK,sBAAsB,MAAM,KAAK;EAC3D,SAAQ,GAAG;AACV,SAAM,IAAI,sBACR,CAAC,wBAAwB,EAAE,KAAK,UAAU,EAAE,GAAG,EAC/C;EAEH;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,GAA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AAI;GACF,cAAc,MAAM,KAAK,sBAAsB,MAAM,KAAK;EAC3D,SAAQ,GAAG;AACV,SAAM,IAAI,sBACR,CAAC,wBAAwB,EAAE,KAAK,UAAU,EAAE,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,o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AAM,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":"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 = parsedResult.children[0] as ParsedResult;\n }\n\n return parseParsedResult(parsedResult);\n}\n"],"mappings":";;;;;;AAQA,MAAa,0BAA0B,CAAC;;;;;;;;;;;;;MAalC,CAAC;AAgBP,IAAa,kBAAb,cAAqC,oCAA+C;CAClF;CAEA,YAAYA,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,SAAO,QAAQ,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,SAAS,SAAS,GAAG;EAC7B,OAAO,MAAM,QAAQ,M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{"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"}
|