@langchain/core 1.1.10 → 1.1.11
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/documents/document.cjs.map +1 -1
- package/dist/documents/document.js.map +1 -1
- package/dist/documents/transformers.cjs.map +1 -1
- package/dist/documents/transformers.js.map +1 -1
- package/dist/example_selectors/conditional.cjs.map +1 -1
- package/dist/example_selectors/conditional.js.map +1 -1
- package/dist/example_selectors/semantic_similarity.cjs.map +1 -1
- package/dist/example_selectors/semantic_similarity.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.cjs.map +1 -1
- package/dist/language_models/chat_models.js.map +1 -1
- package/dist/language_models/llms.cjs.map +1 -1
- package/dist/language_models/llms.js.map +1 -1
- package/dist/load/import_map.cjs +11 -11
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +11 -11
- package/dist/load/import_map.js.map +1 -1
- package/dist/load/index.cjs.map +1 -1
- package/dist/load/index.js.map +1 -1
- package/dist/load/serializable.cjs +3 -3
- package/dist/load/serializable.cjs.map +1 -1
- package/dist/load/serializable.js +3 -3
- package/dist/load/serializable.js.map +1 -1
- package/dist/load/validation.cjs +13 -7
- package/dist/load/validation.cjs.map +1 -1
- package/dist/load/validation.js +13 -7
- package/dist/load/validation.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/chat.cjs.map +1 -1
- package/dist/messages/chat.js.map +1 -1
- package/dist/messages/content/data.cjs.map +1 -1
- package/dist/messages/content/data.js.map +1 -1
- package/dist/messages/content/index.cjs.map +1 -1
- package/dist/messages/content/index.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/human.cjs.map +1 -1
- package/dist/messages/human.js.map +1 -1
- package/dist/messages/message.cjs.map +1 -1
- package/dist/messages/message.js.map +1 -1
- package/dist/messages/modifier.cjs.map +1 -1
- package/dist/messages/modifier.js.map +1 -1
- package/dist/messages/system.cjs.map +1 -1
- package/dist/messages/system.js.map +1 -1
- package/dist/messages/tool.cjs.map +1 -1
- package/dist/messages/tool.js.map +1 -1
- package/dist/messages/utils.cjs.map +1 -1
- package/dist/messages/utils.js.map +1 -1
- package/dist/output_parsers/base.cjs.map +1 -1
- package/dist/output_parsers/base.js.map +1 -1
- package/dist/output_parsers/index.cjs +1 -1
- package/dist/output_parsers/index.js +1 -1
- package/dist/output_parsers/json.cjs.map +1 -1
- package/dist/output_parsers/json.js.map +1 -1
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.cjs.map +1 -1
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.js.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.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/transform.cjs.map +1 -1
- package/dist/output_parsers/transform.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/dict.cjs.map +1 -1
- package/dist/prompts/dict.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/image.cjs.map +1 -1
- package/dist/prompts/image.js.map +1 -1
- package/dist/prompts/pipeline.cjs.map +1 -1
- package/dist/prompts/pipeline.js.map +1 -1
- package/dist/prompts/prompt.cjs.map +1 -1
- package/dist/prompts/prompt.js.map +1 -1
- package/dist/prompts/string.cjs.map +1 -1
- package/dist/prompts/string.js.map +1 -1
- package/dist/prompts/structured.cjs.map +1 -1
- package/dist/prompts/structured.js.map +1 -1
- package/dist/prompts/template.cjs +1 -4
- package/dist/prompts/template.cjs.map +1 -1
- package/dist/prompts/template.js +1 -4
- package/dist/prompts/template.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/branch.cjs.map +1 -1
- package/dist/runnables/branch.js.map +1 -1
- package/dist/runnables/history.cjs.map +1 -1
- package/dist/runnables/history.js.map +1 -1
- package/dist/runnables/passthrough.cjs.map +1 -1
- package/dist/runnables/passthrough.js.map +1 -1
- package/dist/runnables/router.cjs.map +1 -1
- package/dist/runnables/router.js.map +1 -1
- package/dist/singletons/callbacks.cjs.map +1 -1
- package/dist/singletons/callbacks.js.map +1 -1
- package/dist/stores.d.cts.map +1 -1
- package/dist/structured_query/base.cjs.map +1 -1
- package/dist/structured_query/base.js.map +1 -1
- package/dist/structured_query/ir.cjs.map +1 -1
- package/dist/structured_query/ir.js.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/utils/async_caller.cjs.map +1 -1
- package/dist/utils/async_caller.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/utils/types/zod.cjs.map +1 -1
- package/dist/utils/types/zod.js.map +1 -1
- package/dist/vectorstores.cjs.map +1 -1
- package/dist/vectorstores.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_output_tools_parsers.js","names":["rawToolCall: Record<string, any>","options?: { returnId?: boolean; partial?: boolean }","e: any","parsedToolCall: ToolCall","toolCall: ToolCall","errorMsg?: string","fields?: JsonOutputToolsParserParams","generations: ChatGeneration[]","generations: ChatGenerationChunk[] | ChatGeneration[]","rawToolCall: Record<string, unknown>","backwardsCompatibleToolCall: ParsedToolCall","params:\n | JsonOutputKeyToolsParserParamsV3<T>\n | JsonOutputKeyToolsParserParamsV4<T>\n | JsonOutputKeyToolsParserParamsInterop<T>","result: unknown","result: ParsedToolCall","returnedValues: ParsedToolCall[] | Record<string, any>[]"],"sources":["../../../src/output_parsers/openai_tools/json_output_tools_parsers.ts"],"sourcesContent":["import type * as z3 from \"zod/v3\";\nimport type * as z4 from \"zod/v4/core\";\nimport { ChatGeneration, ChatGenerationChunk } from \"../../outputs.js\";\nimport { OutputParserException } from \"../base.js\";\nimport { parsePartialJson } from \"../json.js\";\nimport { InvalidToolCall, ToolCall } from \"../../messages/tool.js\";\nimport {\n BaseCumulativeTransformOutputParser,\n BaseCumulativeTransformOutputParserInput,\n} from \"../transform.js\";\nimport { isAIMessage } from \"../../messages/ai.js\";\nimport {\n type InteropZodType,\n interopSafeParseAsync,\n} from \"../../utils/types/zod.js\";\n\nexport type ParsedToolCall = {\n id?: string;\n\n type: string;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: Record<string, any>;\n};\n\nexport type JsonOutputToolsParserParams = {\n /** Whether to return the tool call id. */\n returnId?: boolean;\n} & BaseCumulativeTransformOutputParserInput;\n\nexport function parseToolCall(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options: { returnId?: boolean; partial: true }\n): ToolCall | undefined;\nexport function parseToolCall(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options?: { returnId?: boolean; partial?: false }\n): ToolCall;\nexport function parseToolCall(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options?: { returnId?: boolean; partial?: boolean }\n): ToolCall | undefined;\nexport function parseToolCall(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options?: { returnId?: boolean; partial?: boolean }\n): ToolCall | undefined {\n if (rawToolCall.function === undefined) {\n return undefined;\n }\n let functionArgs;\n if (options?.partial) {\n try {\n functionArgs = parsePartialJson(rawToolCall.function.arguments ?? \"{}\");\n } catch {\n return undefined;\n }\n } else {\n try {\n functionArgs = JSON.parse(rawToolCall.function.arguments);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new OutputParserException(\n [\n `Function \"${rawToolCall.function.name}\" arguments:`,\n ``,\n rawToolCall.function.arguments,\n ``,\n `are not valid JSON.`,\n `Error: ${e.message}`,\n ].join(\"\\n\")\n );\n }\n }\n\n const parsedToolCall: ToolCall = {\n name: rawToolCall.function.name,\n args: functionArgs,\n type: \"tool_call\",\n };\n\n if (options?.returnId) {\n parsedToolCall.id = rawToolCall.id;\n }\n\n return parsedToolCall;\n}\n\nexport function convertLangChainToolCallToOpenAI(toolCall: ToolCall) {\n if (toolCall.id === undefined) {\n throw new Error(`All OpenAI tool calls must have an \"id\" field.`);\n }\n return {\n id: toolCall.id,\n type: \"function\",\n function: {\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.args),\n },\n };\n}\n\nexport function makeInvalidToolCall(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n errorMsg?: string\n): InvalidToolCall {\n return {\n name: rawToolCall.function?.name,\n args: rawToolCall.function?.arguments,\n id: rawToolCall.id,\n error: errorMsg,\n type: \"invalid_tool_call\",\n };\n}\n\n/**\n * Class for parsing the output of a tool-calling LLM into a JSON object.\n */\nexport class JsonOutputToolsParser<\n T\n> extends BaseCumulativeTransformOutputParser<T> {\n static lc_name() {\n return \"JsonOutputToolsParser\";\n }\n\n returnId = false;\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"openai_tools\"];\n\n lc_serializable = true;\n\n constructor(fields?: JsonOutputToolsParserParams) {\n super(fields);\n this.returnId = fields?.returnId ?? this.returnId;\n }\n\n protected _diff() {\n throw new Error(\"Not supported.\");\n }\n\n async parse(): Promise<T> {\n throw new Error(\"Not implemented.\");\n }\n\n async parseResult(generations: ChatGeneration[]): Promise<T> {\n const result = await this.parsePartialResult(generations, false);\n return result;\n }\n\n /**\n * Parses the output and returns a JSON object. If `argsOnly` is true,\n * only the arguments of the function call are returned.\n * @param generations The output of the LLM to parse.\n * @returns A JSON object representation of the function call or its arguments.\n */\n async parsePartialResult(\n generations: ChatGenerationChunk[] | ChatGeneration[],\n partial = true\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any> {\n const message = generations[0].message;\n let toolCalls;\n if (isAIMessage(message) && message.tool_calls?.length) {\n toolCalls = message.tool_calls.map((toolCall) => {\n const { id, ...rest } = toolCall;\n if (!this.returnId) {\n return rest;\n }\n return {\n id,\n ...rest,\n };\n });\n } else if (message.additional_kwargs.tool_calls !== undefined) {\n const rawToolCalls = JSON.parse(\n JSON.stringify(message.additional_kwargs.tool_calls)\n );\n toolCalls = rawToolCalls.map((rawToolCall: Record<string, unknown>) => {\n return parseToolCall(rawToolCall, { returnId: this.returnId, partial });\n });\n }\n if (!toolCalls) {\n return [];\n }\n const parsedToolCalls = [];\n for (const toolCall of toolCalls) {\n if (toolCall !== undefined) {\n const backwardsCompatibleToolCall: ParsedToolCall = {\n type: toolCall.name,\n args: toolCall.args,\n id: toolCall.id,\n };\n parsedToolCalls.push(backwardsCompatibleToolCall);\n }\n }\n return parsedToolCalls;\n }\n}\n\ntype JsonOutputKeyToolsParserParamsBase = {\n keyName: string;\n returnSingle?: boolean;\n} & JsonOutputToolsParserParams;\n\ntype JsonOutputKeyToolsParserParamsV3<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>\n> = { zodSchema?: z3.ZodType<T> } & JsonOutputKeyToolsParserParamsBase;\n\ntype JsonOutputKeyToolsParserParamsV4<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>\n> = { zodSchema?: z4.$ZodType<T, T> } & JsonOutputKeyToolsParserParamsBase;\n\nexport type JsonOutputKeyToolsParserParamsInterop<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>\n> = { zodSchema?: InteropZodType<T> } & JsonOutputKeyToolsParserParamsBase;\n\n// Use Zod 3 for backwards compatibility\nexport type JsonOutputKeyToolsParserParams<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>\n> = JsonOutputKeyToolsParserParamsV3<T>;\n\n/**\n * Class for parsing the output of a tool-calling LLM into a JSON object if you are\n * expecting only a single tool to be called.\n */\nexport class JsonOutputKeyToolsParser<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>\n> extends JsonOutputToolsParser<T> {\n static lc_name() {\n return \"JsonOutputKeyToolsParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"openai_tools\"];\n\n lc_serializable = true;\n\n returnId = false;\n\n /** The type of tool calls to return. */\n keyName: string;\n\n /** Whether to return only the first tool call. */\n returnSingle = false;\n\n zodSchema?: InteropZodType<T>;\n\n constructor(params: JsonOutputKeyToolsParserParamsV3<T>);\n\n constructor(params: JsonOutputKeyToolsParserParamsV4<T>);\n\n constructor(params: JsonOutputKeyToolsParserParamsInterop<T>);\n\n constructor(\n params:\n | JsonOutputKeyToolsParserParamsV3<T>\n | JsonOutputKeyToolsParserParamsV4<T>\n | JsonOutputKeyToolsParserParamsInterop<T>\n ) {\n super(params);\n this.keyName = params.keyName;\n this.returnSingle = params.returnSingle ?? this.returnSingle;\n this.zodSchema = params.zodSchema;\n }\n\n protected async _validateResult(result: unknown): Promise<T> {\n if (this.zodSchema === undefined) {\n return result as T;\n }\n const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result);\n if (zodParsedResult.success) {\n return zodParsedResult.data;\n } else {\n throw new OutputParserException(\n `Failed to parse. Text: \"${JSON.stringify(\n result,\n null,\n 2\n )}\". Error: ${JSON.stringify(zodParsedResult.error?.issues)}`,\n JSON.stringify(result, null, 2)\n );\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async parsePartialResult(generations: ChatGeneration[]): Promise<any> {\n const results = await super.parsePartialResult(generations);\n const matchingResults = results.filter(\n (result: ParsedToolCall) => result.type === this.keyName\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let returnedValues: ParsedToolCall[] | Record<string, any>[] =\n matchingResults;\n if (!matchingResults.length) {\n return undefined;\n }\n if (!this.returnId) {\n returnedValues = matchingResults.map(\n (result: ParsedToolCall) => result.args\n );\n }\n if (this.returnSingle) {\n return returnedValues[0];\n }\n return returnedValues;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async parseResult(generations: ChatGeneration[]): Promise<any> {\n const results = await super.parsePartialResult(generations, false);\n const matchingResults = results.filter(\n (result: ParsedToolCall) => result.type === this.keyName\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let returnedValues: ParsedToolCall[] | Record<string, any>[] =\n matchingResults;\n if (!matchingResults.length) {\n return undefined;\n }\n if (!this.returnId) {\n returnedValues = matchingResults.map(\n (result: ParsedToolCall) => result.args\n );\n }\n if (this.returnSingle) {\n return this._validateResult(returnedValues[0]);\n }\n const toolCallResults = await Promise.all(\n returnedValues.map((value) => this._validateResult(value))\n );\n return toolCallResults;\n }\n}\n"],"mappings":";;;;;;;;AA6CA,SAAgB,cAEdA,aACAC,SACsB;AACtB,KAAI,YAAY,aAAa,OAC3B,QAAO;CAET,IAAI;AACJ,KAAI,SAAS,QACX,KAAI;EACF,eAAe,iBAAiB,YAAY,SAAS,aAAa,KAAK;CACxE,QAAO;AACN,SAAO;CACR;KAED,KAAI;EACF,eAAe,KAAK,MAAM,YAAY,SAAS,UAAU;CAE1D,SAAQC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KAAK,UAAU,QAAQ,MAAM,EAAE;CAGpC;CAGD,MAAM,mBAAmBL,aAA6C;EACpE,MAAM,UAAU,MAAM,MAAM,mBAAmB,YAAY;EAC3D,MAAM,kBAAkB,QAAQ,OAC9B,CAACM,WAA2B,OAAO,SAAS,KAAK,QAClD;EAED,IAAIC,iBACF;AACF,MAAI,CAAC,gBAAgB,OACnB,QAAO;AAET,MAAI,CAAC,KAAK,UACR,iBAAiB,gBAAgB,IAC/B,CAACD,WAA2B,OAAO,KACpC;AAEH,MAAI,KAAK,aACP,QAAO,eAAe;AAExB,SAAO;CACR;CAGD,MAAM,YAAYN,aAA6C;EAC7D,MAAM,UAAU,MAAM,MAAM,mBAAmB,aAAa,MAAM;EAClE,MAAM,kBAAkB,QAAQ,OAC9B,CAACM,WAA2B,OAAO,SAAS,KAAK,QAClD;EAED,IAAIC,iBACF;AACF,MAAI,CAAC,gBAAgB,OACnB,QAAO;AAET,MAAI,CAAC,KAAK,UACR,iBAAiB,gBAAgB,IAC/B,CAACD,WAA2B,OAAO,KACpC;AAEH,MAAI,KAAK,aACP,QAAO,KAAK,gBAAgB,eAAe,GAAG;EAEhD,MAAM,kBAAkB,MAAM,QAAQ,IACpC,eAAe,IAAI,CAAC,UAAU,KAAK,gBAAgB,MAAM,CAAC,CAC3D;AACD,SAAO;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"json_output_tools_parsers.js","names":["rawToolCall: Record<string, any>","options?: { returnId?: boolean; partial?: boolean }","e: any","parsedToolCall: ToolCall","toolCall: ToolCall","errorMsg?: string","fields?: JsonOutputToolsParserParams","generations: ChatGeneration[]","generations: ChatGenerationChunk[] | ChatGeneration[]","rawToolCall: Record<string, unknown>","backwardsCompatibleToolCall: ParsedToolCall","params:\n | JsonOutputKeyToolsParserParamsV3<T>\n | JsonOutputKeyToolsParserParamsV4<T>\n | JsonOutputKeyToolsParserParamsInterop<T>","result: unknown","result: ParsedToolCall","returnedValues: ParsedToolCall[] | Record<string, any>[]"],"sources":["../../../src/output_parsers/openai_tools/json_output_tools_parsers.ts"],"sourcesContent":["import type * as z3 from \"zod/v3\";\nimport type * as z4 from \"zod/v4/core\";\nimport { ChatGeneration, ChatGenerationChunk } from \"../../outputs.js\";\nimport { OutputParserException } from \"../base.js\";\nimport { parsePartialJson } from \"../json.js\";\nimport { InvalidToolCall, ToolCall } from \"../../messages/tool.js\";\nimport {\n BaseCumulativeTransformOutputParser,\n BaseCumulativeTransformOutputParserInput,\n} from \"../transform.js\";\nimport { isAIMessage } from \"../../messages/ai.js\";\nimport {\n type InteropZodType,\n interopSafeParseAsync,\n} from \"../../utils/types/zod.js\";\n\nexport type ParsedToolCall = {\n id?: string;\n\n type: string;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: Record<string, any>;\n};\n\nexport type JsonOutputToolsParserParams = {\n /** Whether to return the tool call id. */\n returnId?: boolean;\n} & BaseCumulativeTransformOutputParserInput;\n\nexport function parseToolCall(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options: { returnId?: boolean; partial: true }\n): ToolCall | undefined;\nexport function parseToolCall(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options?: { returnId?: boolean; partial?: false }\n): ToolCall;\nexport function parseToolCall(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options?: { returnId?: boolean; partial?: boolean }\n): ToolCall | undefined;\nexport function parseToolCall(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options?: { returnId?: boolean; partial?: boolean }\n): ToolCall | undefined {\n if (rawToolCall.function === undefined) {\n return undefined;\n }\n let functionArgs;\n if (options?.partial) {\n try {\n functionArgs = parsePartialJson(rawToolCall.function.arguments ?? \"{}\");\n } catch {\n return undefined;\n }\n } else {\n try {\n functionArgs = JSON.parse(rawToolCall.function.arguments);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new OutputParserException(\n [\n `Function \"${rawToolCall.function.name}\" arguments:`,\n ``,\n rawToolCall.function.arguments,\n ``,\n `are not valid JSON.`,\n `Error: ${e.message}`,\n ].join(\"\\n\")\n );\n }\n }\n\n const parsedToolCall: ToolCall = {\n name: rawToolCall.function.name,\n args: functionArgs,\n type: \"tool_call\",\n };\n\n if (options?.returnId) {\n parsedToolCall.id = rawToolCall.id;\n }\n\n return parsedToolCall;\n}\n\nexport function convertLangChainToolCallToOpenAI(toolCall: ToolCall) {\n if (toolCall.id === undefined) {\n throw new Error(`All OpenAI tool calls must have an \"id\" field.`);\n }\n return {\n id: toolCall.id,\n type: \"function\",\n function: {\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.args),\n },\n };\n}\n\nexport function makeInvalidToolCall(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n errorMsg?: string\n): InvalidToolCall {\n return {\n name: rawToolCall.function?.name,\n args: rawToolCall.function?.arguments,\n id: rawToolCall.id,\n error: errorMsg,\n type: \"invalid_tool_call\",\n };\n}\n\n/**\n * Class for parsing the output of a tool-calling LLM into a JSON object.\n */\nexport class JsonOutputToolsParser<\n T,\n> extends BaseCumulativeTransformOutputParser<T> {\n static lc_name() {\n return \"JsonOutputToolsParser\";\n }\n\n returnId = false;\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"openai_tools\"];\n\n lc_serializable = true;\n\n constructor(fields?: JsonOutputToolsParserParams) {\n super(fields);\n this.returnId = fields?.returnId ?? this.returnId;\n }\n\n protected _diff() {\n throw new Error(\"Not supported.\");\n }\n\n async parse(): Promise<T> {\n throw new Error(\"Not implemented.\");\n }\n\n async parseResult(generations: ChatGeneration[]): Promise<T> {\n const result = await this.parsePartialResult(generations, false);\n return result;\n }\n\n /**\n * Parses the output and returns a JSON object. If `argsOnly` is true,\n * only the arguments of the function call are returned.\n * @param generations The output of the LLM to parse.\n * @returns A JSON object representation of the function call or its arguments.\n */\n async parsePartialResult(\n generations: ChatGenerationChunk[] | ChatGeneration[],\n partial = true\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any> {\n const message = generations[0].message;\n let toolCalls;\n if (isAIMessage(message) && message.tool_calls?.length) {\n toolCalls = message.tool_calls.map((toolCall) => {\n const { id, ...rest } = toolCall;\n if (!this.returnId) {\n return rest;\n }\n return {\n id,\n ...rest,\n };\n });\n } else if (message.additional_kwargs.tool_calls !== undefined) {\n const rawToolCalls = JSON.parse(\n JSON.stringify(message.additional_kwargs.tool_calls)\n );\n toolCalls = rawToolCalls.map((rawToolCall: Record<string, unknown>) => {\n return parseToolCall(rawToolCall, { returnId: this.returnId, partial });\n });\n }\n if (!toolCalls) {\n return [];\n }\n const parsedToolCalls = [];\n for (const toolCall of toolCalls) {\n if (toolCall !== undefined) {\n const backwardsCompatibleToolCall: ParsedToolCall = {\n type: toolCall.name,\n args: toolCall.args,\n id: toolCall.id,\n };\n parsedToolCalls.push(backwardsCompatibleToolCall);\n }\n }\n return parsedToolCalls;\n }\n}\n\ntype JsonOutputKeyToolsParserParamsBase = {\n keyName: string;\n returnSingle?: boolean;\n} & JsonOutputToolsParserParams;\n\ntype JsonOutputKeyToolsParserParamsV3<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = { zodSchema?: z3.ZodType<T> } & JsonOutputKeyToolsParserParamsBase;\n\ntype JsonOutputKeyToolsParserParamsV4<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = { zodSchema?: z4.$ZodType<T, T> } & JsonOutputKeyToolsParserParamsBase;\n\nexport type JsonOutputKeyToolsParserParamsInterop<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = { zodSchema?: InteropZodType<T> } & JsonOutputKeyToolsParserParamsBase;\n\n// Use Zod 3 for backwards compatibility\nexport type JsonOutputKeyToolsParserParams<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = JsonOutputKeyToolsParserParamsV3<T>;\n\n/**\n * Class for parsing the output of a tool-calling LLM into a JSON object if you are\n * expecting only a single tool to be called.\n */\nexport class JsonOutputKeyToolsParser<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> extends JsonOutputToolsParser<T> {\n static lc_name() {\n return \"JsonOutputKeyToolsParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"openai_tools\"];\n\n lc_serializable = true;\n\n returnId = false;\n\n /** The type of tool calls to return. */\n keyName: string;\n\n /** Whether to return only the first tool call. */\n returnSingle = false;\n\n zodSchema?: InteropZodType<T>;\n\n constructor(params: JsonOutputKeyToolsParserParamsV3<T>);\n\n constructor(params: JsonOutputKeyToolsParserParamsV4<T>);\n\n constructor(params: JsonOutputKeyToolsParserParamsInterop<T>);\n\n constructor(\n params:\n | JsonOutputKeyToolsParserParamsV3<T>\n | JsonOutputKeyToolsParserParamsV4<T>\n | JsonOutputKeyToolsParserParamsInterop<T>\n ) {\n super(params);\n this.keyName = params.keyName;\n this.returnSingle = params.returnSingle ?? this.returnSingle;\n this.zodSchema = params.zodSchema;\n }\n\n protected async _validateResult(result: unknown): Promise<T> {\n if (this.zodSchema === undefined) {\n return result as T;\n }\n const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result);\n if (zodParsedResult.success) {\n return zodParsedResult.data;\n } else {\n throw new OutputParserException(\n `Failed to parse. Text: \"${JSON.stringify(\n result,\n null,\n 2\n )}\". Error: ${JSON.stringify(zodParsedResult.error?.issues)}`,\n JSON.stringify(result, null, 2)\n );\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async parsePartialResult(generations: ChatGeneration[]): Promise<any> {\n const results = await super.parsePartialResult(generations);\n const matchingResults = results.filter(\n (result: ParsedToolCall) => result.type === this.keyName\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let returnedValues: ParsedToolCall[] | Record<string, any>[] =\n matchingResults;\n if (!matchingResults.length) {\n return undefined;\n }\n if (!this.returnId) {\n returnedValues = matchingResults.map(\n (result: ParsedToolCall) => result.args\n );\n }\n if (this.returnSingle) {\n return returnedValues[0];\n }\n return returnedValues;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async parseResult(generations: ChatGeneration[]): Promise<any> {\n const results = await super.parsePartialResult(generations, false);\n const matchingResults = results.filter(\n (result: ParsedToolCall) => result.type === this.keyName\n );\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let returnedValues: ParsedToolCall[] | Record<string, any>[] =\n matchingResults;\n if (!matchingResults.length) {\n return undefined;\n }\n if (!this.returnId) {\n returnedValues = matchingResults.map(\n (result: ParsedToolCall) => result.args\n );\n }\n if (this.returnSingle) {\n return this._validateResult(returnedValues[0]);\n }\n const toolCallResults = await Promise.all(\n returnedValues.map((value) => this._validateResult(value))\n );\n return toolCallResults;\n }\n}\n"],"mappings":";;;;;;;;AA6CA,SAAgB,cAEdA,aACAC,SACsB;AACtB,KAAI,YAAY,aAAa,OAC3B,QAAO;CAET,IAAI;AACJ,KAAI,SAAS,QACX,KAAI;EACF,eAAe,iBAAiB,YAAY,SAAS,aAAa,KAAK;CACxE,QAAO;AACN,SAAO;CACR;KAED,KAAI;EACF,eAAe,KAAK,MAAM,YAAY,SAAS,UAAU;CAE1D,SAAQC,GAAQ;AACf,QAAM,IAAI,sBACR;GACE,CAAC,UAAU,EAAE,YAAY,SAAS,KAAK,YAAY,CAAC;GACpD,EAAE;GACF,YAAY,SAAS;GACrB,EAAE;GACF,CAAC,mBAAmB,CAAC;GACrB,CAAC,OAAO,EAAE,EAAE,SAAS;EACtB,EAAC,KAAK,KAAK;CAEf;CAGH,MAAMC,iBAA2B;EAC/B,MAAM,YAAY,SAAS;EAC3B,MAAM;EACN,MAAM;CACP;AAED,KAAI,SAAS,UACX,eAAe,KAAK,YAAY;AAGlC,QAAO;AACR;AAED,SAAgB,i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;CACR;CAGD,MAAM,YAAYN,aAA6C;EAC7D,MAAM,UAAU,MAAM,MAAM,mBAAmB,aAAa,MAAM;EAClE,MAAM,kBAAkB,QAAQ,OAC9B,CAACM,WAA2B,OAAO,SAAS,KAAK,QAClD;EAED,IAAIC,iBACF;AACF,MAAI,CAAC,gBAAgB,OACnB,QAAO;AAET,MAAI,CAAC,KAAK,UACR,iBAAiB,gBAAgB,IAC/B,CAACD,WAA2B,OAAO,KACpC;AAEH,MAAI,KAAK,aACP,QAAO,KAAK,gBAAgB,eAAe,GAAG;EAEhD,MAAM,kBAAkB,MAAM,QAAQ,IACpC,eAAe,IAAI,CAAC,UAAU,KAAK,gBAAgB,MAAM,CAAC,CAC3D;AACD,SAAO;CACR;AACF"}
|
|
@@ -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;GAC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AAM,YAAY,KAClB,CAAC,MAAMA,SAAE,QAAQ,CAAC,SAAS,YAAY,AAAC,EAC3C,CACF,CACF;AAED,SAAO,IAAI,KAAuB;CACnC;AACF;;;;;AAYD,IAAsB,mCAAtB,cAGUH,8BAAoB;CAC5B,AAAQ;CAER,YAAY,EAAE,aAAwD,EAAE;EACtE,MAAM,GAAG,UAAU;EACnB,KAAK,wBAAwB,IAAI,mCAC/B;CAEH;CAUD,MAAM,MAAMK,MAA0B;EACpC,IAAI;AACJ,MAAI;GACF,cAAc,MAAM,KAAK,sBAAsB,MAAM,KAAK;EAC3D,SAAQ,GAAG;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
|
+
{"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,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ACA,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,KAAuB;CACnC;AACF;;;;;AAYD,IAAsB,mCAAtB,cAGUH,8BAAoB;CAC5B,AAAQ;CAER,YAAY,EAAE,aAAwD,EAAE;EACtE,MAAM,GAAG,UAAU;EACnB,KAAK,wBAAwB,IAAI,mCAC/B;CAEH;CAUD,MAAM,MAAMK,MAA0B;EACpC,IAAI;AACJ,MAAI;GACF,cAAc,MAAM,KAAK,sBAAsB,MAAM,KAAK;EAC3D,SAAQ,GAAG;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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O,IAAI,KAAQ;CACpB;CAED,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,KAAuB;CACnC;AACF;;;;;AAYD,IAAsB,mCAAtB,cAGU,iBAAoB;CAC5B,AAAQ;CAER,YAAY,EAAE,aAAwD,EAAE;EACtE,MAAM,GAAG,UAAU;EACnB,KAAK,wBAAwB,IAAI,mCAC/B;CAEH;CAUD,MAAM,MAAMC,MAA0B;EACpC,IAAI;AACJ,MAAI;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
|
+
{"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,wB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cAAwCP,QAAW;AACxD,SAAO,IAAI,KAAQ;CACpB;CAED,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,KAAuB;CACnC;AACF;;;;;AAYD,IAAsB,mCAAtB,cAGU,iBAAoB;CAC5B,AAAQ;CAER,YAAY,EAAE,aAAwD,EAAE;EACtE,MAAM,GAAG,UAAU;EACnB,KAAK,wBAAwB,IAAI,mCAC/B;CAEH;CAUD,MAAM,MAAMC,MAA0B;EACpC,IAAI;AACJ,MAAI;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":"transform.cjs","names":["BaseOutputParser","inputGenerator: AsyncGenerator<string | BaseMessage>","options: BaseCallbackConfig","fields?: BaseCumulativeTransformOutputParserInput","prevParsed: T | undefined","accGen: GenerationChunk | undefined","chunkGen: GenerationChunk","isBaseMessageChunk","ChatGenerationChunk","isBaseMessage","convertToChunk","GenerationChunk"],"sources":["../../src/output_parsers/transform.ts"],"sourcesContent":["import { deepCompareStrict } from \"@cfworker/json-schema\";\nimport { BaseOutputParser } from \"./base.js\";\nimport {\n type BaseMessage,\n isBaseMessage,\n isBaseMessageChunk,\n} from \"../messages/base.js\";\nimport { convertToChunk } from \"../messages/utils.js\";\nimport type { BaseCallbackConfig } from \"../callbacks/manager.js\";\nimport {\n type Generation,\n type ChatGeneration,\n GenerationChunk,\n ChatGenerationChunk,\n} from \"../outputs.js\";\n\n/**\n * Class to parse the output of an LLM call that also allows streaming inputs.\n */\nexport abstract class BaseTransformOutputParser<\n T = unknown
|
|
1
|
+
{"version":3,"file":"transform.cjs","names":["BaseOutputParser","inputGenerator: AsyncGenerator<string | BaseMessage>","options: BaseCallbackConfig","fields?: BaseCumulativeTransformOutputParserInput","prevParsed: T | undefined","accGen: GenerationChunk | undefined","chunkGen: GenerationChunk","isBaseMessageChunk","ChatGenerationChunk","isBaseMessage","convertToChunk","GenerationChunk"],"sources":["../../src/output_parsers/transform.ts"],"sourcesContent":["import { deepCompareStrict } from \"@cfworker/json-schema\";\nimport { BaseOutputParser } from \"./base.js\";\nimport {\n type BaseMessage,\n isBaseMessage,\n isBaseMessageChunk,\n} from \"../messages/base.js\";\nimport { convertToChunk } from \"../messages/utils.js\";\nimport type { BaseCallbackConfig } from \"../callbacks/manager.js\";\nimport {\n type Generation,\n type ChatGeneration,\n GenerationChunk,\n ChatGenerationChunk,\n} from \"../outputs.js\";\n\n/**\n * Class to parse the output of an LLM call that also allows streaming inputs.\n */\nexport abstract class BaseTransformOutputParser<\n T = unknown,\n> extends BaseOutputParser<T> {\n async *_transform(\n inputGenerator: AsyncGenerator<string | BaseMessage>\n ): AsyncGenerator<T> {\n for await (const chunk of inputGenerator) {\n if (typeof chunk === \"string\") {\n yield this.parseResult([{ text: chunk }]);\n } else {\n yield this.parseResult([\n {\n message: chunk,\n text: this._baseMessageToString(chunk),\n },\n ]);\n }\n }\n }\n\n /**\n * Transforms an asynchronous generator of input into an asynchronous\n * generator of parsed output.\n * @param inputGenerator An asynchronous generator of input.\n * @param options A configuration object.\n * @returns An asynchronous generator of parsed output.\n */\n async *transform(\n inputGenerator: AsyncGenerator<string | BaseMessage>,\n options: BaseCallbackConfig\n ): AsyncGenerator<T> {\n yield* this._transformStreamWithConfig(\n inputGenerator,\n this._transform.bind(this),\n {\n ...options,\n runType: \"parser\",\n }\n );\n }\n}\n\nexport type BaseCumulativeTransformOutputParserInput = { diff?: boolean };\n\n/**\n * A base class for output parsers that can handle streaming input. It\n * extends the `BaseTransformOutputParser` class and provides a method for\n * converting parsed outputs into a diff format.\n */\nexport abstract class BaseCumulativeTransformOutputParser<\n T = unknown,\n> extends BaseTransformOutputParser<T> {\n protected diff = false;\n\n constructor(fields?: BaseCumulativeTransformOutputParserInput) {\n super(fields);\n this.diff = fields?.diff ?? this.diff;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected abstract _diff(prev: any | undefined, next: any): any;\n\n abstract parsePartialResult(\n generations: Generation[] | ChatGeneration[]\n ): Promise<T | undefined>;\n\n async *_transform(\n inputGenerator: AsyncGenerator<string | BaseMessage>\n ): AsyncGenerator<T> {\n let prevParsed: T | undefined;\n let accGen: GenerationChunk | undefined;\n for await (const chunk of inputGenerator) {\n if (typeof chunk !== \"string\" && typeof chunk.content !== \"string\") {\n throw new Error(\"Cannot handle non-string output.\");\n }\n let chunkGen: GenerationChunk;\n if (isBaseMessageChunk(chunk)) {\n if (typeof chunk.content !== \"string\") {\n throw new Error(\"Cannot handle non-string message output.\");\n }\n chunkGen = new ChatGenerationChunk({\n message: chunk,\n text: chunk.content,\n });\n } else if (isBaseMessage(chunk)) {\n if (typeof chunk.content !== \"string\") {\n throw new Error(\"Cannot handle non-string message output.\");\n }\n chunkGen = new ChatGenerationChunk({\n message: convertToChunk(chunk),\n text: chunk.content,\n });\n } else {\n chunkGen = new GenerationChunk({ text: chunk });\n }\n\n if (accGen === undefined) {\n accGen = chunkGen;\n } else {\n accGen = accGen.concat(chunkGen);\n }\n\n const parsed = await this.parsePartialResult([accGen]);\n if (\n parsed !== undefined &&\n parsed !== null &&\n !deepCompareStrict(parsed, prevParsed)\n ) {\n if (this.diff) {\n yield this._diff(prevParsed, parsed);\n } else {\n yield parsed;\n }\n prevParsed = parsed;\n }\n }\n }\n\n getFormatInstructions(): string {\n return \"\";\n }\n}\n"],"mappings":";;;;;;;;;;;AAmBA,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AmB,QAAQ,WAAW,EACtC;AACA,QAAI,KAAK,MACP,MAAM,KAAK,MAAM,YAAY,OAAO;SAEpC,MAAM;IAER,aAAa;GACd;EACF;CACF;CAED,wBAAgC;AAC9B,SAAO;CACR;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transform.js","names":["inputGenerator: AsyncGenerator<string | BaseMessage>","options: BaseCallbackConfig","fields?: BaseCumulativeTransformOutputParserInput","prevParsed: T | undefined","accGen: GenerationChunk | undefined","chunkGen: GenerationChunk"],"sources":["../../src/output_parsers/transform.ts"],"sourcesContent":["import { deepCompareStrict } from \"@cfworker/json-schema\";\nimport { BaseOutputParser } from \"./base.js\";\nimport {\n type BaseMessage,\n isBaseMessage,\n isBaseMessageChunk,\n} from \"../messages/base.js\";\nimport { convertToChunk } from \"../messages/utils.js\";\nimport type { BaseCallbackConfig } from \"../callbacks/manager.js\";\nimport {\n type Generation,\n type ChatGeneration,\n GenerationChunk,\n ChatGenerationChunk,\n} from \"../outputs.js\";\n\n/**\n * Class to parse the output of an LLM call that also allows streaming inputs.\n */\nexport abstract class BaseTransformOutputParser<\n T = unknown
|
|
1
|
+
{"version":3,"file":"transform.js","names":["inputGenerator: AsyncGenerator<string | BaseMessage>","options: BaseCallbackConfig","fields?: BaseCumulativeTransformOutputParserInput","prevParsed: T | undefined","accGen: GenerationChunk | undefined","chunkGen: GenerationChunk"],"sources":["../../src/output_parsers/transform.ts"],"sourcesContent":["import { deepCompareStrict } from \"@cfworker/json-schema\";\nimport { BaseOutputParser } from \"./base.js\";\nimport {\n type BaseMessage,\n isBaseMessage,\n isBaseMessageChunk,\n} from \"../messages/base.js\";\nimport { convertToChunk } from \"../messages/utils.js\";\nimport type { BaseCallbackConfig } from \"../callbacks/manager.js\";\nimport {\n type Generation,\n type ChatGeneration,\n GenerationChunk,\n ChatGenerationChunk,\n} from \"../outputs.js\";\n\n/**\n * Class to parse the output of an LLM call that also allows streaming inputs.\n */\nexport abstract class BaseTransformOutputParser<\n T = unknown,\n> extends BaseOutputParser<T> {\n async *_transform(\n inputGenerator: AsyncGenerator<string | BaseMessage>\n ): AsyncGenerator<T> {\n for await (const chunk of inputGenerator) {\n if (typeof chunk === \"string\") {\n yield this.parseResult([{ text: chunk }]);\n } else {\n yield this.parseResult([\n {\n message: chunk,\n text: this._baseMessageToString(chunk),\n },\n ]);\n }\n }\n }\n\n /**\n * Transforms an asynchronous generator of input into an asynchronous\n * generator of parsed output.\n * @param inputGenerator An asynchronous generator of input.\n * @param options A configuration object.\n * @returns An asynchronous generator of parsed output.\n */\n async *transform(\n inputGenerator: AsyncGenerator<string | BaseMessage>,\n options: BaseCallbackConfig\n ): AsyncGenerator<T> {\n yield* this._transformStreamWithConfig(\n inputGenerator,\n this._transform.bind(this),\n {\n ...options,\n runType: \"parser\",\n }\n );\n }\n}\n\nexport type BaseCumulativeTransformOutputParserInput = { diff?: boolean };\n\n/**\n * A base class for output parsers that can handle streaming input. It\n * extends the `BaseTransformOutputParser` class and provides a method for\n * converting parsed outputs into a diff format.\n */\nexport abstract class BaseCumulativeTransformOutputParser<\n T = unknown,\n> extends BaseTransformOutputParser<T> {\n protected diff = false;\n\n constructor(fields?: BaseCumulativeTransformOutputParserInput) {\n super(fields);\n this.diff = fields?.diff ?? this.diff;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected abstract _diff(prev: any | undefined, next: any): any;\n\n abstract parsePartialResult(\n generations: Generation[] | ChatGeneration[]\n ): Promise<T | undefined>;\n\n async *_transform(\n inputGenerator: AsyncGenerator<string | BaseMessage>\n ): AsyncGenerator<T> {\n let prevParsed: T | undefined;\n let accGen: GenerationChunk | undefined;\n for await (const chunk of inputGenerator) {\n if (typeof chunk !== \"string\" && typeof chunk.content !== \"string\") {\n throw new Error(\"Cannot handle non-string output.\");\n }\n let chunkGen: GenerationChunk;\n if (isBaseMessageChunk(chunk)) {\n if (typeof chunk.content !== \"string\") {\n throw new Error(\"Cannot handle non-string message output.\");\n }\n chunkGen = new ChatGenerationChunk({\n message: chunk,\n text: chunk.content,\n });\n } else if (isBaseMessage(chunk)) {\n if (typeof chunk.content !== \"string\") {\n throw new Error(\"Cannot handle non-string message output.\");\n }\n chunkGen = new ChatGenerationChunk({\n message: convertToChunk(chunk),\n text: chunk.content,\n });\n } else {\n chunkGen = new GenerationChunk({ text: chunk });\n }\n\n if (accGen === undefined) {\n accGen = chunkGen;\n } else {\n accGen = accGen.concat(chunkGen);\n }\n\n const parsed = await this.parsePartialResult([accGen]);\n if (\n parsed !== undefined &&\n parsed !== null &&\n !deepCompareStrict(parsed, prevParsed)\n ) {\n if (this.diff) {\n yield this._diff(prevParsed, parsed);\n } else {\n yield parsed;\n }\n prevParsed = parsed;\n }\n }\n }\n\n getFormatInstructions(): string {\n return \"\";\n }\n}\n"],"mappings":";;;;;;;;;;AAmBA,IAAsB,4BAAtB,cAEU,iBAAoB;CAC5B,OAAO,WACLA,gBACmB;AACnB,aAAW,MAAM,SAAS,eACxB,KAAI,OAAO,UAAU,UACnB,MAAM,KAAK,YAAY,CAAC,EAAE,MAAM,MAAO,CAAC,EAAC;OAEzC,MAAM,KAAK,YAAY,CACrB;GACE,SAAS;GACT,MAAM,KAAK,qBAAqB,MAAM;EACvC,CACF,EAAC;CAGP;;;;;;;;CASD,OAAO,UACLA,gBACAC,SACmB;EACnB,OAAO,KAAK,2BACV,gBACA,KAAK,WAAW,KAAK,KAAK,EAC1B;GACE,GAAG;GACH,SAAS;EACV,EACF;CACF;AACF;;;;;;AASD,IAAsB,sCAAtB,cAEU,0BAA6B;CACrC,AAAU,OAAO;CAEjB,YAAYC,QAAmD;EAC7D,MAAM,OAAO;EACb,KAAK,OAAO,QAAQ,QAAQ,KAAK;CAClC;CASD,OAAO,WACLF,gBACmB;EACnB,IAAIG;EACJ,IAAIC;AACJ,aAAW,MAAM,SAAS,gBAAgB;AACxC,OAAI,OAAO,UAAU,YAAY,OAAO,MAAM,YAAY,SACxD,OAAM,IAAI,MAAM;GAElB,IAAIC;AACJ,OAAI,mBAAmB,MAAM,EAAE;AAC7B,QAAI,OAAO,MAAM,YAAY,SAC3B,OAAM,IAAI,MAAM;IAElB,WAAW,IAAI,oBAAoB;KACjC,SAAS;KACT,MAAM,MAAM;IACb;GACF,WAAU,cAAc,MAAM,EAAE;AAC/B,QAAI,OAAO,MAAM,YAAY,SAC3B,OAAM,IAAI,MAAM;IAElB,WAAW,IAAI,oBAAoB;KACjC,SAAS,eAAe,MAAM;KAC9B,MAAM,MAAM;IACb;GACF,OACC,WAAW,IAAI,gBAAgB,EAAE,MAAM,MAAO;AAGhD,OAAI,WAAW,QACb,SAAS;QAET,SAAS,OAAO,OAAO,SAAS;GAGlC,MAAM,SAAS,MAAM,KAAK,mBAAmB,CAAC,MAAO,EAAC;AACtD,OACE,WAAW,UACX,WAAW,QACX,CAAC,kBAAkB,QAAQ,WAAW,EACtC;AACA,QAAI,KAAK,MACP,MAAM,KAAK,MAAM,YAAY,OAAO;SAEpC,MAAM;IAER,aAAa;GACd;EACF;CACF;CAED,wBAAgC;AAC9B,SAAO;CACR;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.cjs","names":["Runnable","input: BasePromptTemplateInput","userVariables: TypedPromptInputValues<RunInput>","partialValues: Record<string, string>","input: RunInput","options?: BaseCallbackConfig","input"],"sources":["../../src/prompts/base.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport type {\n InputValues,\n PartialValues,\n StringWithAutocomplete,\n} from \"../utils/types/index.js\";\nimport { type BasePromptValueInterface } from \"../prompt_values.js\";\nimport { BaseOutputParser } from \"../output_parsers/index.js\";\nimport type { SerializedFields } from \"../load/map_keys.js\";\nimport { Runnable } from \"../runnables/base.js\";\nimport { BaseCallbackConfig } from \"../callbacks/manager.js\";\n\nexport type TypedPromptInputValues<RunInput> = InputValues<\n StringWithAutocomplete<Extract<keyof RunInput, string>>\n>;\n\nexport type Example = Record<string, string>;\n\n/**\n * Input common to all prompt templates.\n */\nexport interface BasePromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n InputVariables extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any
|
|
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
|
|
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"}
|