@langchain/core 1.1.29 → 1.1.30
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 +16 -0
- package/dist/language_models/base.cjs +1 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.d.cts +6 -0
- package/dist/language_models/base.d.cts.map +1 -1
- package/dist/language_models/base.d.ts +6 -0
- package/dist/language_models/base.d.ts.map +1 -1
- package/dist/language_models/base.js +1 -1
- package/dist/language_models/base.js.map +1 -1
- package/dist/language_models/chat_models.cjs +8 -23
- package/dist/language_models/chat_models.cjs.map +1 -1
- package/dist/language_models/chat_models.d.cts +6 -0
- package/dist/language_models/chat_models.d.cts.map +1 -1
- package/dist/language_models/chat_models.d.ts +6 -0
- package/dist/language_models/chat_models.d.ts.map +1 -1
- package/dist/language_models/chat_models.js +9 -24
- package/dist/language_models/chat_models.js.map +1 -1
- package/dist/language_models/structured_output.cjs +88 -0
- package/dist/language_models/structured_output.cjs.map +1 -0
- package/dist/language_models/structured_output.d.cts +46 -0
- package/dist/language_models/structured_output.d.cts.map +1 -0
- package/dist/language_models/structured_output.d.ts +50 -0
- package/dist/language_models/structured_output.d.ts.map +1 -0
- package/dist/language_models/structured_output.js +79 -0
- package/dist/language_models/structured_output.js.map +1 -0
- package/dist/load/import_map.cjs +8 -4
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +8 -4
- package/dist/load/import_map.js.map +1 -1
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.d.cts +2 -2
- package/dist/messages/base.d.cts.map +1 -1
- package/dist/messages/base.d.ts +2 -2
- package/dist/messages/base.d.ts.map +1 -1
- package/dist/messages/base.js.map +1 -1
- package/dist/output_parsers/index.cjs +4 -1
- package/dist/output_parsers/index.cjs.map +1 -1
- package/dist/output_parsers/index.d.cts +2 -1
- package/dist/output_parsers/index.d.ts +2 -1
- package/dist/output_parsers/index.js +4 -2
- package/dist/output_parsers/index.js.map +1 -1
- package/dist/output_parsers/openai_tools/index.d.cts +2 -2
- package/dist/output_parsers/openai_tools/index.d.ts +2 -2
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs +8 -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.d.cts +6 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.cts.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.ts +6 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.ts.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.js +8 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.js.map +1 -1
- package/dist/output_parsers/standard_schema.cjs +40 -0
- package/dist/output_parsers/standard_schema.cjs.map +1 -0
- package/dist/output_parsers/standard_schema.d.cts +16 -0
- package/dist/output_parsers/standard_schema.d.cts.map +1 -0
- package/dist/output_parsers/standard_schema.d.ts +16 -0
- package/dist/output_parsers/standard_schema.d.ts.map +1 -0
- package/dist/output_parsers/standard_schema.js +40 -0
- package/dist/output_parsers/standard_schema.js.map +1 -0
- package/dist/utils/json_schema.cjs +3 -1
- package/dist/utils/json_schema.cjs.map +1 -1
- package/dist/utils/json_schema.d.cts +3 -2
- package/dist/utils/json_schema.d.cts.map +1 -1
- package/dist/utils/json_schema.d.ts +3 -2
- package/dist/utils/json_schema.d.ts.map +1 -1
- package/dist/utils/json_schema.js +3 -1
- package/dist/utils/json_schema.js.map +1 -1
- package/dist/utils/standard_schema.cjs +43 -0
- package/dist/utils/standard_schema.cjs.map +1 -0
- package/dist/utils/standard_schema.d.cts +27 -0
- package/dist/utils/standard_schema.d.cts.map +1 -0
- package/dist/utils/standard_schema.d.ts +27 -0
- package/dist/utils/standard_schema.d.ts.map +1 -0
- package/dist/utils/standard_schema.js +34 -0
- package/dist/utils/standard_schema.js.map +1 -0
- package/dist/utils/testing/fake_model_builder.cjs +174 -0
- package/dist/utils/testing/fake_model_builder.cjs.map +1 -0
- package/dist/utils/testing/fake_model_builder.d.cts +87 -0
- package/dist/utils/testing/fake_model_builder.d.cts.map +1 -0
- package/dist/utils/testing/fake_model_builder.d.ts +88 -0
- package/dist/utils/testing/fake_model_builder.d.ts.map +1 -0
- package/dist/utils/testing/fake_model_builder.js +174 -0
- package/dist/utils/testing/fake_model_builder.js.map +1 -0
- package/dist/utils/testing/index.cjs +4 -1
- package/dist/utils/testing/index.cjs.map +1 -1
- package/dist/utils/testing/index.d.cts +2 -1
- package/dist/utils/testing/index.d.ts +2 -1
- package/dist/utils/testing/index.js +4 -2
- package/dist/utils/testing/index.js.map +1 -1
- package/dist/utils/types/zod.cjs +1 -1
- package/dist/utils/types/zod.cjs.map +1 -1
- package/dist/utils/types/zod.d.cts +3 -2
- package/dist/utils/types/zod.d.cts.map +1 -1
- package/dist/utils/types/zod.d.ts +3 -2
- package/dist/utils/types/zod.d.ts.map +1 -1
- package/dist/utils/types/zod.js +1 -1
- package/dist/utils/types/zod.js.map +1 -1
- package/errors.cjs +1 -0
- package/errors.d.cts +1 -0
- package/errors.d.ts +1 -0
- package/errors.js +1 -0
- package/language_models/structured_output.cjs +1 -0
- package/language_models/structured_output.d.cts +1 -0
- package/language_models/structured_output.d.ts +1 -0
- package/language_models/structured_output.js +1 -0
- package/package.json +32 -5
- package/utils/standard_schema.cjs +1 -0
- package/utils/standard_schema.d.cts +1 -0
- package/utils/standard_schema.d.ts +1 -0
- package/utils/standard_schema.js +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_output_tools_parsers.js","names":[],"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":"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"}
|
|
1
|
+
{"version":3,"file":"json_output_tools_parsers.js","names":[],"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\";\nimport { SerializableSchema } from \"../../utils/standard_schema.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\nexport type JsonOutputKeyToolsParserParamsSerializable<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = {\n serializableSchema?: SerializableSchema<T>;\n} & 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 serializableSchema?: SerializableSchema<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 | JsonOutputKeyToolsParserParamsSerializable<T>\n ) {\n super(params);\n this.keyName = params.keyName;\n this.returnSingle = params.returnSingle ?? this.returnSingle;\n if (\"zodSchema\" in params) {\n this.zodSchema = params.zodSchema;\n }\n if (\"serializableSchema\" in params) {\n this.serializableSchema = params.serializableSchema;\n }\n }\n\n protected async _validateResult(result: unknown): Promise<T> {\n if (this.serializableSchema !== undefined) {\n const validated =\n await this.serializableSchema[\"~standard\"].validate(result);\n if (validated.issues) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${JSON.stringify(\n result,\n null,\n 2\n )}\". Error: ${JSON.stringify(validated.issues)}`,\n JSON.stringify(result, null, 2)\n );\n }\n return validated.value as T;\n }\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":"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"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const require_json = require('../utils/json.cjs');
|
|
2
|
+
const require_base = require('./base.cjs');
|
|
3
|
+
require('./json.cjs');
|
|
4
|
+
|
|
5
|
+
//#region src/output_parsers/standard_schema.ts
|
|
6
|
+
var StandardSchemaOutputParser = class extends require_base.BaseOutputParser {
|
|
7
|
+
static lc_name() {
|
|
8
|
+
return "StandardSchemaOutputParser";
|
|
9
|
+
}
|
|
10
|
+
lc_namespace = [
|
|
11
|
+
"langchain",
|
|
12
|
+
"output_parsers",
|
|
13
|
+
"standard_schema"
|
|
14
|
+
];
|
|
15
|
+
schema;
|
|
16
|
+
constructor(schema) {
|
|
17
|
+
super();
|
|
18
|
+
this.schema = schema;
|
|
19
|
+
}
|
|
20
|
+
static fromSerializableSchema(schema) {
|
|
21
|
+
return new this(schema);
|
|
22
|
+
}
|
|
23
|
+
async parse(text) {
|
|
24
|
+
try {
|
|
25
|
+
const json = require_json.parseJsonMarkdown(text, JSON.parse);
|
|
26
|
+
const result = await this.schema["~standard"].validate(json);
|
|
27
|
+
if (result.issues) throw new Error(`Validation failed: ${JSON.stringify(result.issues)}`);
|
|
28
|
+
return result.value;
|
|
29
|
+
} catch (e) {
|
|
30
|
+
throw new require_base.OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
getFormatInstructions() {
|
|
34
|
+
return "";
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
//#endregion
|
|
39
|
+
exports.StandardSchemaOutputParser = StandardSchemaOutputParser;
|
|
40
|
+
//# sourceMappingURL=standard_schema.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard_schema.cjs","names":["BaseOutputParser","parseJsonMarkdown","OutputParserException"],"sources":["../../src/output_parsers/standard_schema.ts"],"sourcesContent":["import { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { BaseOutputParser, OutputParserException } from \"./base.js\";\nimport { parseJsonMarkdown } from \"./json.js\";\n\nexport class StandardSchemaOutputParser<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n> extends BaseOutputParser<RunOutput> {\n static lc_name() {\n return \"StandardSchemaOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"standard_schema\"];\n\n private readonly schema: StandardSchemaV1<RunOutput>;\n\n constructor(schema: StandardSchemaV1<RunOutput>) {\n super();\n this.schema = schema;\n }\n\n static fromSerializableSchema<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(schema: StandardSchemaV1<RunOutput>) {\n return new this(schema);\n }\n\n async parse(text: string): Promise<RunOutput> {\n try {\n const json = parseJsonMarkdown(text, JSON.parse);\n const result = await this.schema[\"~standard\"].validate(json);\n if (result.issues) {\n throw new Error(`Validation failed: ${JSON.stringify(result.issues)}`);\n }\n return result.value as RunOutput;\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n }\n\n getFormatInstructions(): string {\n return \"\";\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,6BAAb,cAGUA,8BAA4B;CACpC,OAAO,UAAU;AACf,SAAO;;CAGT,eAAe;EAAC;EAAa;EAAkB;EAAkB;CAEjE,AAAiB;CAEjB,YAAY,QAAqC;AAC/C,SAAO;AACP,OAAK,SAAS;;CAGhB,OAAO,uBAGL,QAAqC;AACrC,SAAO,IAAI,KAAK,OAAO;;CAGzB,MAAM,MAAM,MAAkC;AAC5C,MAAI;GACF,MAAM,OAAOC,+BAAkB,MAAM,KAAK,MAAM;GAChD,MAAM,SAAS,MAAM,KAAK,OAAO,aAAa,SAAS,KAAK;AAC5D,OAAI,OAAO,OACT,OAAM,IAAI,MAAM,sBAAsB,KAAK,UAAU,OAAO,OAAO,GAAG;AAExE,UAAO,OAAO;WACP,GAAG;AACV,SAAM,IAAIC,mCACR,2BAA2B,KAAK,YAAY,KAC5C,KACD;;;CAIL,wBAAgC;AAC9B,SAAO"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { BaseOutputParser } from "./base.cjs";
|
|
2
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
|
+
|
|
4
|
+
//#region src/output_parsers/standard_schema.d.ts
|
|
5
|
+
declare class StandardSchemaOutputParser<RunOutput extends Record<string, any> = Record<string, any>> extends BaseOutputParser<RunOutput> {
|
|
6
|
+
static lc_name(): string;
|
|
7
|
+
lc_namespace: string[];
|
|
8
|
+
private readonly schema;
|
|
9
|
+
constructor(schema: StandardSchemaV1<RunOutput>);
|
|
10
|
+
static fromSerializableSchema<RunOutput extends Record<string, any> = Record<string, any>>(schema: StandardSchemaV1<RunOutput>): StandardSchemaOutputParser<RunOutput>;
|
|
11
|
+
parse(text: string): Promise<RunOutput>;
|
|
12
|
+
getFormatInstructions(): string;
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { StandardSchemaOutputParser };
|
|
16
|
+
//# sourceMappingURL=standard_schema.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard_schema.d.cts","names":[],"sources":["../../src/output_parsers/standard_schema.ts"],"mappings":";;;;cAIa,0BAAA,mBAEO,MAAA,gBAAsB,MAAA,uBAChC,gBAAA,CAAiB,SAAA;EAAA,OAClB,OAAA,CAAA;EAIP,YAAA;EAAA,iBAEiB,MAAA;EAEjB,WAAA,CAAY,MAAA,EAAQ,gBAAA,CAAiB,SAAA;EAAA,OAK9B,sBAAA,mBAEa,MAAA,gBAAsB,MAAA,cAAA,CACxC,MAAA,EAAQ,gBAAA,CAAiB,SAAA,IAAU,0BAAA,CAAA,SAAA;EAI/B,KAAA,CAAM,IAAA,WAAe,OAAA,CAAQ,SAAA;EAgBnC,qBAAA,CAAA;AAAA"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { BaseOutputParser } from "./base.js";
|
|
2
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
|
+
|
|
4
|
+
//#region src/output_parsers/standard_schema.d.ts
|
|
5
|
+
declare class StandardSchemaOutputParser<RunOutput extends Record<string, any> = Record<string, any>> extends BaseOutputParser<RunOutput> {
|
|
6
|
+
static lc_name(): string;
|
|
7
|
+
lc_namespace: string[];
|
|
8
|
+
private readonly schema;
|
|
9
|
+
constructor(schema: StandardSchemaV1<RunOutput>);
|
|
10
|
+
static fromSerializableSchema<RunOutput extends Record<string, any> = Record<string, any>>(schema: StandardSchemaV1<RunOutput>): StandardSchemaOutputParser<RunOutput>;
|
|
11
|
+
parse(text: string): Promise<RunOutput>;
|
|
12
|
+
getFormatInstructions(): string;
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { StandardSchemaOutputParser };
|
|
16
|
+
//# sourceMappingURL=standard_schema.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard_schema.d.ts","names":[],"sources":["../../src/output_parsers/standard_schema.ts"],"mappings":";;;;cAIa,0BAAA,mBAEO,MAAA,gBAAsB,MAAA,uBAChC,gBAAA,CAAiB,SAAA;EAAA,OAClB,OAAA,CAAA;EAIP,YAAA;EAAA,iBAEiB,MAAA;EAEjB,WAAA,CAAY,MAAA,EAAQ,gBAAA,CAAiB,SAAA;EAAA,OAK9B,sBAAA,mBAEa,MAAA,gBAAsB,MAAA,cAAA,CACxC,MAAA,EAAQ,gBAAA,CAAiB,SAAA,IAAU,0BAAA,CAAA,SAAA;EAI/B,KAAA,CAAM,IAAA,WAAe,OAAA,CAAQ,SAAA;EAgBnC,qBAAA,CAAA;AAAA"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { parseJsonMarkdown } from "../utils/json.js";
|
|
2
|
+
import { BaseOutputParser, OutputParserException } from "./base.js";
|
|
3
|
+
import "./json.js";
|
|
4
|
+
|
|
5
|
+
//#region src/output_parsers/standard_schema.ts
|
|
6
|
+
var StandardSchemaOutputParser = class extends BaseOutputParser {
|
|
7
|
+
static lc_name() {
|
|
8
|
+
return "StandardSchemaOutputParser";
|
|
9
|
+
}
|
|
10
|
+
lc_namespace = [
|
|
11
|
+
"langchain",
|
|
12
|
+
"output_parsers",
|
|
13
|
+
"standard_schema"
|
|
14
|
+
];
|
|
15
|
+
schema;
|
|
16
|
+
constructor(schema) {
|
|
17
|
+
super();
|
|
18
|
+
this.schema = schema;
|
|
19
|
+
}
|
|
20
|
+
static fromSerializableSchema(schema) {
|
|
21
|
+
return new this(schema);
|
|
22
|
+
}
|
|
23
|
+
async parse(text) {
|
|
24
|
+
try {
|
|
25
|
+
const json = parseJsonMarkdown(text, JSON.parse);
|
|
26
|
+
const result = await this.schema["~standard"].validate(json);
|
|
27
|
+
if (result.issues) throw new Error(`Validation failed: ${JSON.stringify(result.issues)}`);
|
|
28
|
+
return result.value;
|
|
29
|
+
} catch (e) {
|
|
30
|
+
throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
getFormatInstructions() {
|
|
34
|
+
return "";
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
//#endregion
|
|
39
|
+
export { StandardSchemaOutputParser };
|
|
40
|
+
//# sourceMappingURL=standard_schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard_schema.js","names":[],"sources":["../../src/output_parsers/standard_schema.ts"],"sourcesContent":["import { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { BaseOutputParser, OutputParserException } from \"./base.js\";\nimport { parseJsonMarkdown } from \"./json.js\";\n\nexport class StandardSchemaOutputParser<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n> extends BaseOutputParser<RunOutput> {\n static lc_name() {\n return \"StandardSchemaOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"standard_schema\"];\n\n private readonly schema: StandardSchemaV1<RunOutput>;\n\n constructor(schema: StandardSchemaV1<RunOutput>) {\n super();\n this.schema = schema;\n }\n\n static fromSerializableSchema<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(schema: StandardSchemaV1<RunOutput>) {\n return new this(schema);\n }\n\n async parse(text: string): Promise<RunOutput> {\n try {\n const json = parseJsonMarkdown(text, JSON.parse);\n const result = await this.schema[\"~standard\"].validate(json);\n if (result.issues) {\n throw new Error(`Validation failed: ${JSON.stringify(result.issues)}`);\n }\n return result.value as RunOutput;\n } catch (e) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${text}\". Error: ${e}`,\n text\n );\n }\n }\n\n getFormatInstructions(): string {\n return \"\";\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,6BAAb,cAGU,iBAA4B;CACpC,OAAO,UAAU;AACf,SAAO;;CAGT,eAAe;EAAC;EAAa;EAAkB;EAAkB;CAEjE,AAAiB;CAEjB,YAAY,QAAqC;AAC/C,SAAO;AACP,OAAK,SAAS;;CAGhB,OAAO,uBAGL,QAAqC;AACrC,SAAO,IAAI,KAAK,OAAO;;CAGzB,MAAM,MAAM,MAAkC;AAC5C,MAAI;GACF,MAAM,OAAO,kBAAkB,MAAM,KAAK,MAAM;GAChD,MAAM,SAAS,MAAM,KAAK,OAAO,aAAa,SAAS,KAAK;AAC5D,OAAI,OAAO,OACT,OAAM,IAAI,MAAM,sBAAsB,KAAK,UAAU,OAAO,OAAO,GAAG;AAExE,UAAO,OAAO;WACP,GAAG;AACV,SAAM,IAAI,sBACR,2BAA2B,KAAK,YAAY,KAC5C,KACD;;;CAIL,wBAAgC;AAC9B,SAAO"}
|
|
@@ -3,6 +3,7 @@ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
|
3
3
|
const require_zod = require('./types/zod.cjs');
|
|
4
4
|
const require_zodToJsonSchema = require('./zod-to-json-schema/zodToJsonSchema.cjs');
|
|
5
5
|
require('./zod-to-json-schema/index.cjs');
|
|
6
|
+
const require_utils_standard_schema = require('./standard_schema.cjs');
|
|
6
7
|
let zod_v4_core = require("zod/v4/core");
|
|
7
8
|
let _cfworker_json_schema = require("@cfworker/json-schema");
|
|
8
9
|
|
|
@@ -14,12 +15,13 @@ var json_schema_exports = /* @__PURE__ */ require_runtime.__exportAll({
|
|
|
14
15
|
validatesOnlyStrings: () => validatesOnlyStrings
|
|
15
16
|
});
|
|
16
17
|
/**
|
|
17
|
-
* Converts a Zod schema or JSON schema to a JSON schema.
|
|
18
|
+
* Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema.
|
|
18
19
|
* @param schema - The schema to convert.
|
|
19
20
|
* @param params - The parameters to pass to the toJSONSchema function.
|
|
20
21
|
* @returns The converted schema.
|
|
21
22
|
*/
|
|
22
23
|
function toJsonSchema(schema, params) {
|
|
24
|
+
if (require_utils_standard_schema.isStandardJsonSchema(schema) && !require_zod.isZodSchemaV4(schema)) return schema["~standard"].jsonSchema.input({ target: "draft-07" });
|
|
23
25
|
if (require_zod.isZodSchemaV4(schema)) {
|
|
24
26
|
const inputSchema = require_zod.interopZodTransformInputSchema(schema, true);
|
|
25
27
|
if (require_zod.isZodObjectV4(inputSchema)) return (0, zod_v4_core.toJSONSchema)(require_zod.interopZodObjectStrict(inputSchema, true), params);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_schema.cjs","names":["isZodSchemaV4","interopZodTransformInputSchema","isZodObjectV4","interopZodObjectStrict","isZodSchemaV3","zodToJsonSchema"],"sources":["../../src/utils/json_schema.ts"],"sourcesContent":["import { toJSONSchema } from \"zod/v4/core\";\nimport { dereference, type Schema } from \"@cfworker/json-schema\";\nimport {\n isZodSchemaV3,\n isZodSchemaV4,\n InteropZodType,\n interopZodObjectStrict,\n isZodObjectV4,\n ZodObjectV4,\n interopZodTransformInputSchema,\n} from \"./types/zod.js\";\nimport {\n type JsonSchema7Type as JSONSchema,\n zodToJsonSchema,\n} from \"./zod-to-json-schema/index.js\";\n\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n\nexport type ToJSONSchemaParams = NonNullable<\n Parameters<typeof toJSONSchema>[1]\n>;\n\n/**\n * Converts a Zod schema or JSON schema to a JSON schema.\n * @param schema - The schema to convert.\n * @param params - The parameters to pass to the toJSONSchema function.\n * @returns The converted schema.\n */\nexport function toJsonSchema(\n schema: InteropZodType | JSONSchema,\n params?: ToJSONSchemaParams\n): JSONSchema {\n if (isZodSchemaV4(schema)) {\n const inputSchema = interopZodTransformInputSchema(schema, true);\n if (isZodObjectV4(inputSchema)) {\n const strictSchema = interopZodObjectStrict(\n inputSchema,\n true\n ) as ZodObjectV4;\n return toJSONSchema(strictSchema, params);\n } else {\n return toJSONSchema(schema, params);\n }\n }\n if (isZodSchemaV3(schema)) {\n return zodToJsonSchema(schema);\n }\n return schema as JSONSchema;\n}\n\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport function validatesOnlyStrings(schema: unknown): boolean {\n // Null, undefined, or empty schema\n if (\n !schema ||\n typeof schema !== \"object\" ||\n Object.keys(schema).length === 0 ||\n Array.isArray(schema)\n ) {\n return false; // Validates anything, not just strings\n }\n\n // Explicit type constraint\n if (\"type\" in schema) {\n if (typeof schema.type === \"string\") {\n return schema.type === \"string\";\n }\n\n if (Array.isArray(schema.type)) {\n // not sure why someone would do `\"type\": [\"string\"]` or especially `\"type\": [\"string\",\n // \"string\", \"string\", ...]` but we're not here to judge\n return schema.type.every((t) => t === \"string\");\n }\n return false; // Invalid or non-string type\n }\n\n // Enum with only string values\n if (\"enum\" in schema) {\n return (\n Array.isArray(schema.enum) &&\n schema.enum.length > 0 &&\n schema.enum.every((val) => typeof val === \"string\")\n );\n }\n\n // String constant\n if (\"const\" in schema) {\n return typeof schema.const === \"string\";\n }\n\n // Schema combinations\n if (\"allOf\" in schema && Array.isArray(schema.allOf)) {\n // If any subschema validates only strings, then the overall schema validates only strings\n return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n }\n\n if (\n (\"anyOf\" in schema && Array.isArray(schema.anyOf)) ||\n (\"oneOf\" in schema && Array.isArray(schema.oneOf))\n ) {\n const subschemas = (\n \"anyOf\" in schema ? schema.anyOf : schema.oneOf\n ) as unknown[];\n\n // All subschemas must validate only strings\n return (\n subschemas.length > 0 &&\n subschemas.every((subschema) => validatesOnlyStrings(subschema))\n );\n }\n\n // We're not going to try on this one, it's too complex - we just assume if it has a \"not\" key and hasn't matched one of the above checks, it's not a string schema.\n if (\"not\" in schema) {\n return false; // The not case can validate non-strings\n }\n\n if (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n const ref = schema.$ref as string;\n const resolved = dereference(schema as Schema);\n if (resolved[ref]) {\n return validatesOnlyStrings(resolved[ref]);\n }\n return false;\n }\n\n // ignore recursive refs and other cases where type is omitted for now\n // ignore other cases for now where type is omitted\n\n return false;\n}\n\n// Re-export of the types used throughout langchain for json schema serialization.\n// The plan is to eventually nix zod-to-json-schema altogether in place for\n// zod v4 / a more standardized way of serializing validated inputs, so its re-exported\n// here to remove the dependency on zod-to-json-schema in downstream packages until\n// a determination is made.\n\nexport {\n type JsonSchema7Type,\n type JsonSchema7Type as JSONSchema,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"./zod-to-json-schema/index.js\";\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"json_schema.cjs","names":["isStandardJsonSchema","isZodSchemaV4","interopZodTransformInputSchema","isZodObjectV4","interopZodObjectStrict","isZodSchemaV3","zodToJsonSchema"],"sources":["../../src/utils/json_schema.ts"],"sourcesContent":["import { toJSONSchema } from \"zod/v4/core\";\nimport { dereference, type Schema } from \"@cfworker/json-schema\";\nimport {\n isZodSchemaV3,\n isZodSchemaV4,\n InteropZodType,\n interopZodObjectStrict,\n isZodObjectV4,\n ZodObjectV4,\n interopZodTransformInputSchema,\n} from \"./types/zod.js\";\nimport {\n type JsonSchema7Type as JSONSchema,\n zodToJsonSchema,\n} from \"./zod-to-json-schema/index.js\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { isStandardJsonSchema } from \"./standard_schema.js\";\n\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n\nexport type ToJSONSchemaParams = NonNullable<\n Parameters<typeof toJSONSchema>[1]\n>;\n\n/**\n * Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema.\n * @param schema - The schema to convert.\n * @param params - The parameters to pass to the toJSONSchema function.\n * @returns The converted schema.\n */\nexport function toJsonSchema(\n schema: StandardJSONSchemaV1 | InteropZodType | JSONSchema,\n params?: ToJSONSchemaParams\n): JSONSchema {\n if (isStandardJsonSchema(schema) && !isZodSchemaV4(schema)) {\n return schema[\"~standard\"].jsonSchema.input({\n target: \"draft-07\",\n }) as JSONSchema;\n }\n if (isZodSchemaV4(schema)) {\n const inputSchema = interopZodTransformInputSchema(schema, true);\n if (isZodObjectV4(inputSchema)) {\n const strictSchema = interopZodObjectStrict(\n inputSchema,\n true\n ) as ZodObjectV4;\n return toJSONSchema(strictSchema, params);\n } else {\n return toJSONSchema(schema, params);\n }\n }\n if (isZodSchemaV3(schema)) {\n return zodToJsonSchema(schema);\n }\n return schema as JSONSchema;\n}\n\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport function validatesOnlyStrings(schema: unknown): boolean {\n // Null, undefined, or empty schema\n if (\n !schema ||\n typeof schema !== \"object\" ||\n Object.keys(schema).length === 0 ||\n Array.isArray(schema)\n ) {\n return false; // Validates anything, not just strings\n }\n\n // Explicit type constraint\n if (\"type\" in schema) {\n if (typeof schema.type === \"string\") {\n return schema.type === \"string\";\n }\n\n if (Array.isArray(schema.type)) {\n // not sure why someone would do `\"type\": [\"string\"]` or especially `\"type\": [\"string\",\n // \"string\", \"string\", ...]` but we're not here to judge\n return schema.type.every((t) => t === \"string\");\n }\n return false; // Invalid or non-string type\n }\n\n // Enum with only string values\n if (\"enum\" in schema) {\n return (\n Array.isArray(schema.enum) &&\n schema.enum.length > 0 &&\n schema.enum.every((val) => typeof val === \"string\")\n );\n }\n\n // String constant\n if (\"const\" in schema) {\n return typeof schema.const === \"string\";\n }\n\n // Schema combinations\n if (\"allOf\" in schema && Array.isArray(schema.allOf)) {\n // If any subschema validates only strings, then the overall schema validates only strings\n return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n }\n\n if (\n (\"anyOf\" in schema && Array.isArray(schema.anyOf)) ||\n (\"oneOf\" in schema && Array.isArray(schema.oneOf))\n ) {\n const subschemas = (\n \"anyOf\" in schema ? schema.anyOf : schema.oneOf\n ) as unknown[];\n\n // All subschemas must validate only strings\n return (\n subschemas.length > 0 &&\n subschemas.every((subschema) => validatesOnlyStrings(subschema))\n );\n }\n\n // We're not going to try on this one, it's too complex - we just assume if it has a \"not\" key and hasn't matched one of the above checks, it's not a string schema.\n if (\"not\" in schema) {\n return false; // The not case can validate non-strings\n }\n\n if (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n const ref = schema.$ref as string;\n const resolved = dereference(schema as Schema);\n if (resolved[ref]) {\n return validatesOnlyStrings(resolved[ref]);\n }\n return false;\n }\n\n // ignore recursive refs and other cases where type is omitted for now\n // ignore other cases for now where type is omitted\n\n return false;\n}\n\n// Re-export of the types used throughout langchain for json schema serialization.\n// The plan is to eventually nix zod-to-json-schema altogether in place for\n// zod v4 / a more standardized way of serializing validated inputs, so its re-exported\n// here to remove the dependency on zod-to-json-schema in downstream packages until\n// a determination is made.\n\nexport {\n type JsonSchema7Type,\n type JsonSchema7Type as JSONSchema,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"./zod-to-json-schema/index.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,aACd,QACA,QACY;AACZ,KAAIA,mDAAqB,OAAO,IAAI,CAACC,0BAAc,OAAO,CACxD,QAAO,OAAO,aAAa,WAAW,MAAM,EAC1C,QAAQ,YACT,CAAC;AAEJ,KAAIA,0BAAc,OAAO,EAAE;EACzB,MAAM,cAAcC,2CAA+B,QAAQ,KAAK;AAChE,MAAIC,0BAAc,YAAY,CAK5B,sCAJqBC,mCACnB,aACA,KACD,EACiC,OAAO;MAEzC,sCAAoB,QAAQ,OAAO;;AAGvC,KAAIC,0BAAc,OAAO,CACvB,QAAOC,wCAAgB,OAAO;AAEhC,QAAO;;;;;;;;;AAUT,SAAgB,qBAAqB,QAA0B;AAE7D,KACE,CAAC,UACD,OAAO,WAAW,YAClB,OAAO,KAAK,OAAO,CAAC,WAAW,KAC/B,MAAM,QAAQ,OAAO,CAErB,QAAO;AAIT,KAAI,UAAU,QAAQ;AACpB,MAAI,OAAO,OAAO,SAAS,SACzB,QAAO,OAAO,SAAS;AAGzB,MAAI,MAAM,QAAQ,OAAO,KAAK,CAG5B,QAAO,OAAO,KAAK,OAAO,MAAM,MAAM,SAAS;AAEjD,SAAO;;AAIT,KAAI,UAAU,OACZ,QACE,MAAM,QAAQ,OAAO,KAAK,IAC1B,OAAO,KAAK,SAAS,KACrB,OAAO,KAAK,OAAO,QAAQ,OAAO,QAAQ,SAAS;AAKvD,KAAI,WAAW,OACb,QAAO,OAAO,OAAO,UAAU;AAIjC,KAAI,WAAW,UAAU,MAAM,QAAQ,OAAO,MAAM,CAElD,QAAO,OAAO,MAAM,MAAM,cAAc,qBAAqB,UAAU,CAAC;AAG1E,KACG,WAAW,UAAU,MAAM,QAAQ,OAAO,MAAM,IAChD,WAAW,UAAU,MAAM,QAAQ,OAAO,MAAM,EACjD;EACA,MAAM,aACJ,WAAW,SAAS,OAAO,QAAQ,OAAO;AAI5C,SACE,WAAW,SAAS,KACpB,WAAW,OAAO,cAAc,qBAAqB,UAAU,CAAC;;AAKpE,KAAI,SAAS,OACX,QAAO;AAGT,KAAI,UAAU,UAAU,OAAO,OAAO,SAAS,UAAU;EACvD,MAAM,MAAM,OAAO;EACnB,MAAM,kDAAuB,OAAiB;AAC9C,MAAI,SAAS,KACX,QAAO,qBAAqB,SAAS,KAAK;AAE5C,SAAO;;AAMT,QAAO"}
|
|
@@ -6,17 +6,18 @@ import { JsonSchema7NullableType } from "./zod-to-json-schema/parsers/nullable.c
|
|
|
6
6
|
import { JsonSchema7ObjectType } from "./zod-to-json-schema/parsers/object.cjs";
|
|
7
7
|
import { JsonSchema7Type } from "./zod-to-json-schema/parseTypes.cjs";
|
|
8
8
|
import { toJSONSchema } from "zod/v4/core";
|
|
9
|
+
import { StandardJSONSchemaV1 } from "@standard-schema/spec";
|
|
9
10
|
import { Validator, deepCompareStrict } from "@cfworker/json-schema";
|
|
10
11
|
|
|
11
12
|
//#region src/utils/json_schema.d.ts
|
|
12
13
|
type ToJSONSchemaParams = NonNullable<Parameters<typeof toJSONSchema>[1]>;
|
|
13
14
|
/**
|
|
14
|
-
* Converts a Zod schema or JSON schema to a JSON schema.
|
|
15
|
+
* Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema.
|
|
15
16
|
* @param schema - The schema to convert.
|
|
16
17
|
* @param params - The parameters to pass to the toJSONSchema function.
|
|
17
18
|
* @returns The converted schema.
|
|
18
19
|
*/
|
|
19
|
-
declare function toJsonSchema(schema: InteropZodType | JsonSchema7Type, params?: ToJSONSchemaParams): JsonSchema7Type;
|
|
20
|
+
declare function toJsonSchema(schema: StandardJSONSchemaV1 | InteropZodType | JsonSchema7Type, params?: ToJSONSchemaParams): JsonSchema7Type;
|
|
20
21
|
/**
|
|
21
22
|
* Validates if a JSON schema validates only strings. May return false negatives in some edge cases
|
|
22
23
|
* (like recursive or unresolvable refs).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_schema.d.cts","names":[],"sources":["../../src/utils/json_schema.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"json_schema.d.cts","names":[],"sources":["../../src/utils/json_schema.ts"],"mappings":";;;;;;;;;;;;KAoBY,kBAAA,GAAqB,WAAA,CAC/B,UAAA,QAAkB,YAAA;;;;;;;iBASJ,YAAA,CACd,MAAA,EAAQ,oBAAA,GAAuB,cAAA,GAAiB,eAAA,EAChD,MAAA,GAAS,kBAAA,GACR,eAAA;;;;;;;;iBA+Ba,oBAAA,CAAqB,MAAA"}
|
|
@@ -8,16 +8,17 @@ import { JsonSchema7Type } from "./zod-to-json-schema/parseTypes.js";
|
|
|
8
8
|
import "./zod-to-json-schema/index.js";
|
|
9
9
|
import { toJSONSchema } from "zod/v4/core";
|
|
10
10
|
import { Validator, deepCompareStrict } from "@cfworker/json-schema";
|
|
11
|
+
import { StandardJSONSchemaV1 } from "@standard-schema/spec";
|
|
11
12
|
|
|
12
13
|
//#region src/utils/json_schema.d.ts
|
|
13
14
|
type ToJSONSchemaParams = NonNullable<Parameters<typeof toJSONSchema>[1]>;
|
|
14
15
|
/**
|
|
15
|
-
* Converts a Zod schema or JSON schema to a JSON schema.
|
|
16
|
+
* Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema.
|
|
16
17
|
* @param schema - The schema to convert.
|
|
17
18
|
* @param params - The parameters to pass to the toJSONSchema function.
|
|
18
19
|
* @returns The converted schema.
|
|
19
20
|
*/
|
|
20
|
-
declare function toJsonSchema(schema: InteropZodType | JsonSchema7Type, params?: ToJSONSchemaParams): JsonSchema7Type;
|
|
21
|
+
declare function toJsonSchema(schema: StandardJSONSchemaV1 | InteropZodType | JsonSchema7Type, params?: ToJSONSchemaParams): JsonSchema7Type;
|
|
21
22
|
/**
|
|
22
23
|
* Validates if a JSON schema validates only strings. May return false negatives in some edge cases
|
|
23
24
|
* (like recursive or unresolvable refs).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_schema.d.ts","names":[],"sources":["../../src/utils/json_schema.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"json_schema.d.ts","names":[],"sources":["../../src/utils/json_schema.ts"],"mappings":";;;;;;;;;;;;;KAoBY,kBAAA,GAAqB,WAAA,CAC/B,UAAA,QAAkB,YAAA;;;;;;;iBASJ,YAAA,CACd,MAAA,EAAQ,oBAAA,GAAuB,cAAA,GAAiB,eAAA,EAChD,MAAA,GAAS,kBAAA,GACR,eAAA;AAbH;;;;;;;AAAA,iBA4CgB,oBAAA,CAAqB,MAAA"}
|
|
@@ -2,6 +2,7 @@ import { __exportAll } from "../_virtual/_rolldown/runtime.js";
|
|
|
2
2
|
import { interopZodObjectStrict, interopZodTransformInputSchema, isZodObjectV4, isZodSchemaV3, isZodSchemaV4 } from "./types/zod.js";
|
|
3
3
|
import { zodToJsonSchema } from "./zod-to-json-schema/zodToJsonSchema.js";
|
|
4
4
|
import "./zod-to-json-schema/index.js";
|
|
5
|
+
import { isStandardJsonSchema } from "./standard_schema.js";
|
|
5
6
|
import { toJSONSchema } from "zod/v4/core";
|
|
6
7
|
import { Validator, deepCompareStrict, dereference } from "@cfworker/json-schema";
|
|
7
8
|
|
|
@@ -13,12 +14,13 @@ var json_schema_exports = /* @__PURE__ */ __exportAll({
|
|
|
13
14
|
validatesOnlyStrings: () => validatesOnlyStrings
|
|
14
15
|
});
|
|
15
16
|
/**
|
|
16
|
-
* Converts a Zod schema or JSON schema to a JSON schema.
|
|
17
|
+
* Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema.
|
|
17
18
|
* @param schema - The schema to convert.
|
|
18
19
|
* @param params - The parameters to pass to the toJSONSchema function.
|
|
19
20
|
* @returns The converted schema.
|
|
20
21
|
*/
|
|
21
22
|
function toJsonSchema(schema, params) {
|
|
23
|
+
if (isStandardJsonSchema(schema) && !isZodSchemaV4(schema)) return schema["~standard"].jsonSchema.input({ target: "draft-07" });
|
|
22
24
|
if (isZodSchemaV4(schema)) {
|
|
23
25
|
const inputSchema = interopZodTransformInputSchema(schema, true);
|
|
24
26
|
if (isZodObjectV4(inputSchema)) return toJSONSchema(interopZodObjectStrict(inputSchema, true), params);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_schema.js","names":[],"sources":["../../src/utils/json_schema.ts"],"sourcesContent":["import { toJSONSchema } from \"zod/v4/core\";\nimport { dereference, type Schema } from \"@cfworker/json-schema\";\nimport {\n isZodSchemaV3,\n isZodSchemaV4,\n InteropZodType,\n interopZodObjectStrict,\n isZodObjectV4,\n ZodObjectV4,\n interopZodTransformInputSchema,\n} from \"./types/zod.js\";\nimport {\n type JsonSchema7Type as JSONSchema,\n zodToJsonSchema,\n} from \"./zod-to-json-schema/index.js\";\n\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n\nexport type ToJSONSchemaParams = NonNullable<\n Parameters<typeof toJSONSchema>[1]\n>;\n\n/**\n * Converts a Zod schema or JSON schema to a JSON schema.\n * @param schema - The schema to convert.\n * @param params - The parameters to pass to the toJSONSchema function.\n * @returns The converted schema.\n */\nexport function toJsonSchema(\n schema: InteropZodType | JSONSchema,\n params?: ToJSONSchemaParams\n): JSONSchema {\n if (isZodSchemaV4(schema)) {\n const inputSchema = interopZodTransformInputSchema(schema, true);\n if (isZodObjectV4(inputSchema)) {\n const strictSchema = interopZodObjectStrict(\n inputSchema,\n true\n ) as ZodObjectV4;\n return toJSONSchema(strictSchema, params);\n } else {\n return toJSONSchema(schema, params);\n }\n }\n if (isZodSchemaV3(schema)) {\n return zodToJsonSchema(schema);\n }\n return schema as JSONSchema;\n}\n\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport function validatesOnlyStrings(schema: unknown): boolean {\n // Null, undefined, or empty schema\n if (\n !schema ||\n typeof schema !== \"object\" ||\n Object.keys(schema).length === 0 ||\n Array.isArray(schema)\n ) {\n return false; // Validates anything, not just strings\n }\n\n // Explicit type constraint\n if (\"type\" in schema) {\n if (typeof schema.type === \"string\") {\n return schema.type === \"string\";\n }\n\n if (Array.isArray(schema.type)) {\n // not sure why someone would do `\"type\": [\"string\"]` or especially `\"type\": [\"string\",\n // \"string\", \"string\", ...]` but we're not here to judge\n return schema.type.every((t) => t === \"string\");\n }\n return false; // Invalid or non-string type\n }\n\n // Enum with only string values\n if (\"enum\" in schema) {\n return (\n Array.isArray(schema.enum) &&\n schema.enum.length > 0 &&\n schema.enum.every((val) => typeof val === \"string\")\n );\n }\n\n // String constant\n if (\"const\" in schema) {\n return typeof schema.const === \"string\";\n }\n\n // Schema combinations\n if (\"allOf\" in schema && Array.isArray(schema.allOf)) {\n // If any subschema validates only strings, then the overall schema validates only strings\n return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n }\n\n if (\n (\"anyOf\" in schema && Array.isArray(schema.anyOf)) ||\n (\"oneOf\" in schema && Array.isArray(schema.oneOf))\n ) {\n const subschemas = (\n \"anyOf\" in schema ? schema.anyOf : schema.oneOf\n ) as unknown[];\n\n // All subschemas must validate only strings\n return (\n subschemas.length > 0 &&\n subschemas.every((subschema) => validatesOnlyStrings(subschema))\n );\n }\n\n // We're not going to try on this one, it's too complex - we just assume if it has a \"not\" key and hasn't matched one of the above checks, it's not a string schema.\n if (\"not\" in schema) {\n return false; // The not case can validate non-strings\n }\n\n if (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n const ref = schema.$ref as string;\n const resolved = dereference(schema as Schema);\n if (resolved[ref]) {\n return validatesOnlyStrings(resolved[ref]);\n }\n return false;\n }\n\n // ignore recursive refs and other cases where type is omitted for now\n // ignore other cases for now where type is omitted\n\n return false;\n}\n\n// Re-export of the types used throughout langchain for json schema serialization.\n// The plan is to eventually nix zod-to-json-schema altogether in place for\n// zod v4 / a more standardized way of serializing validated inputs, so its re-exported\n// here to remove the dependency on zod-to-json-schema in downstream packages until\n// a determination is made.\n\nexport {\n type JsonSchema7Type,\n type JsonSchema7Type as JSONSchema,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"./zod-to-json-schema/index.js\";\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"json_schema.js","names":[],"sources":["../../src/utils/json_schema.ts"],"sourcesContent":["import { toJSONSchema } from \"zod/v4/core\";\nimport { dereference, type Schema } from \"@cfworker/json-schema\";\nimport {\n isZodSchemaV3,\n isZodSchemaV4,\n InteropZodType,\n interopZodObjectStrict,\n isZodObjectV4,\n ZodObjectV4,\n interopZodTransformInputSchema,\n} from \"./types/zod.js\";\nimport {\n type JsonSchema7Type as JSONSchema,\n zodToJsonSchema,\n} from \"./zod-to-json-schema/index.js\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { isStandardJsonSchema } from \"./standard_schema.js\";\n\nexport { deepCompareStrict, Validator } from \"@cfworker/json-schema\";\n\nexport type ToJSONSchemaParams = NonNullable<\n Parameters<typeof toJSONSchema>[1]\n>;\n\n/**\n * Converts a Standard JSON schema, Zod schema or JSON schema to a JSON schema.\n * @param schema - The schema to convert.\n * @param params - The parameters to pass to the toJSONSchema function.\n * @returns The converted schema.\n */\nexport function toJsonSchema(\n schema: StandardJSONSchemaV1 | InteropZodType | JSONSchema,\n params?: ToJSONSchemaParams\n): JSONSchema {\n if (isStandardJsonSchema(schema) && !isZodSchemaV4(schema)) {\n return schema[\"~standard\"].jsonSchema.input({\n target: \"draft-07\",\n }) as JSONSchema;\n }\n if (isZodSchemaV4(schema)) {\n const inputSchema = interopZodTransformInputSchema(schema, true);\n if (isZodObjectV4(inputSchema)) {\n const strictSchema = interopZodObjectStrict(\n inputSchema,\n true\n ) as ZodObjectV4;\n return toJSONSchema(strictSchema, params);\n } else {\n return toJSONSchema(schema, params);\n }\n }\n if (isZodSchemaV3(schema)) {\n return zodToJsonSchema(schema);\n }\n return schema as JSONSchema;\n}\n\n/**\n * Validates if a JSON schema validates only strings. May return false negatives in some edge cases\n * (like recursive or unresolvable refs).\n *\n * @param schema - The schema to validate.\n * @returns `true` if the schema validates only strings, `false` otherwise.\n */\nexport function validatesOnlyStrings(schema: unknown): boolean {\n // Null, undefined, or empty schema\n if (\n !schema ||\n typeof schema !== \"object\" ||\n Object.keys(schema).length === 0 ||\n Array.isArray(schema)\n ) {\n return false; // Validates anything, not just strings\n }\n\n // Explicit type constraint\n if (\"type\" in schema) {\n if (typeof schema.type === \"string\") {\n return schema.type === \"string\";\n }\n\n if (Array.isArray(schema.type)) {\n // not sure why someone would do `\"type\": [\"string\"]` or especially `\"type\": [\"string\",\n // \"string\", \"string\", ...]` but we're not here to judge\n return schema.type.every((t) => t === \"string\");\n }\n return false; // Invalid or non-string type\n }\n\n // Enum with only string values\n if (\"enum\" in schema) {\n return (\n Array.isArray(schema.enum) &&\n schema.enum.length > 0 &&\n schema.enum.every((val) => typeof val === \"string\")\n );\n }\n\n // String constant\n if (\"const\" in schema) {\n return typeof schema.const === \"string\";\n }\n\n // Schema combinations\n if (\"allOf\" in schema && Array.isArray(schema.allOf)) {\n // If any subschema validates only strings, then the overall schema validates only strings\n return schema.allOf.some((subschema) => validatesOnlyStrings(subschema));\n }\n\n if (\n (\"anyOf\" in schema && Array.isArray(schema.anyOf)) ||\n (\"oneOf\" in schema && Array.isArray(schema.oneOf))\n ) {\n const subschemas = (\n \"anyOf\" in schema ? schema.anyOf : schema.oneOf\n ) as unknown[];\n\n // All subschemas must validate only strings\n return (\n subschemas.length > 0 &&\n subschemas.every((subschema) => validatesOnlyStrings(subschema))\n );\n }\n\n // We're not going to try on this one, it's too complex - we just assume if it has a \"not\" key and hasn't matched one of the above checks, it's not a string schema.\n if (\"not\" in schema) {\n return false; // The not case can validate non-strings\n }\n\n if (\"$ref\" in schema && typeof schema.$ref === \"string\") {\n const ref = schema.$ref as string;\n const resolved = dereference(schema as Schema);\n if (resolved[ref]) {\n return validatesOnlyStrings(resolved[ref]);\n }\n return false;\n }\n\n // ignore recursive refs and other cases where type is omitted for now\n // ignore other cases for now where type is omitted\n\n return false;\n}\n\n// Re-export of the types used throughout langchain for json schema serialization.\n// The plan is to eventually nix zod-to-json-schema altogether in place for\n// zod v4 / a more standardized way of serializing validated inputs, so its re-exported\n// here to remove the dependency on zod-to-json-schema in downstream packages until\n// a determination is made.\n\nexport {\n type JsonSchema7Type,\n type JsonSchema7Type as JSONSchema,\n type JsonSchema7ArrayType,\n type JsonSchema7ObjectType,\n type JsonSchema7StringType,\n type JsonSchema7NumberType,\n type JsonSchema7NullableType,\n} from \"./zod-to-json-schema/index.js\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,aACd,QACA,QACY;AACZ,KAAI,qBAAqB,OAAO,IAAI,CAAC,cAAc,OAAO,CACxD,QAAO,OAAO,aAAa,WAAW,MAAM,EAC1C,QAAQ,YACT,CAAC;AAEJ,KAAI,cAAc,OAAO,EAAE;EACzB,MAAM,cAAc,+BAA+B,QAAQ,KAAK;AAChE,MAAI,cAAc,YAAY,CAK5B,QAAO,aAJc,uBACnB,aACA,KACD,EACiC,OAAO;MAEzC,QAAO,aAAa,QAAQ,OAAO;;AAGvC,KAAI,cAAc,OAAO,CACvB,QAAO,gBAAgB,OAAO;AAEhC,QAAO;;;;;;;;;AAUT,SAAgB,qBAAqB,QAA0B;AAE7D,KACE,CAAC,UACD,OAAO,WAAW,YAClB,OAAO,KAAK,OAAO,CAAC,WAAW,KAC/B,MAAM,QAAQ,OAAO,CAErB,QAAO;AAIT,KAAI,UAAU,QAAQ;AACpB,MAAI,OAAO,OAAO,SAAS,SACzB,QAAO,OAAO,SAAS;AAGzB,MAAI,MAAM,QAAQ,OAAO,KAAK,CAG5B,QAAO,OAAO,KAAK,OAAO,MAAM,MAAM,SAAS;AAEjD,SAAO;;AAIT,KAAI,UAAU,OACZ,QACE,MAAM,QAAQ,OAAO,KAAK,IAC1B,OAAO,KAAK,SAAS,KACrB,OAAO,KAAK,OAAO,QAAQ,OAAO,QAAQ,SAAS;AAKvD,KAAI,WAAW,OACb,QAAO,OAAO,OAAO,UAAU;AAIjC,KAAI,WAAW,UAAU,MAAM,QAAQ,OAAO,MAAM,CAElD,QAAO,OAAO,MAAM,MAAM,cAAc,qBAAqB,UAAU,CAAC;AAG1E,KACG,WAAW,UAAU,MAAM,QAAQ,OAAO,MAAM,IAChD,WAAW,UAAU,MAAM,QAAQ,OAAO,MAAM,EACjD;EACA,MAAM,aACJ,WAAW,SAAS,OAAO,QAAQ,OAAO;AAI5C,SACE,WAAW,SAAS,KACpB,WAAW,OAAO,cAAc,qBAAqB,UAAU,CAAC;;AAKpE,KAAI,SAAS,OACX,QAAO;AAGT,KAAI,UAAU,UAAU,OAAO,OAAO,SAAS,UAAU;EACvD,MAAM,MAAM,OAAO;EACnB,MAAM,WAAW,YAAY,OAAiB;AAC9C,MAAI,SAAS,KACX,QAAO,qBAAqB,SAAS,KAAK;AAE5C,SAAO;;AAMT,QAAO"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
3
|
+
|
|
4
|
+
//#region src/utils/standard_schema.ts
|
|
5
|
+
var standard_schema_exports = /* @__PURE__ */ require_runtime.__exportAll({
|
|
6
|
+
isSerializableSchema: () => isSerializableSchema,
|
|
7
|
+
isStandardJsonSchema: () => isStandardJsonSchema,
|
|
8
|
+
isStandardSchema: () => isStandardSchema
|
|
9
|
+
});
|
|
10
|
+
/**
|
|
11
|
+
* Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate`
|
|
12
|
+
* interface, indicating it can validate unknown values at runtime (e.g. for parsing LLM output).
|
|
13
|
+
*/
|
|
14
|
+
function isStandardSchema(schema) {
|
|
15
|
+
return (typeof schema === "object" || typeof schema === "function") && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "validate" in schema["~standard"];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Type guard for Standard JSON Schema V1. Returns true if the value has a `~standard.jsonSchema`
|
|
19
|
+
* interface, indicating it can be converted to a JSON Schema object (e.g. for sending as a tool
|
|
20
|
+
* definition to an LLM).
|
|
21
|
+
*/
|
|
22
|
+
function isStandardJsonSchema(schema) {
|
|
23
|
+
return (typeof schema === "object" || typeof schema === "function") && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "jsonSchema" in schema["~standard"];
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate` interface,
|
|
27
|
+
* indicating it can validate unknown values at runtime (e.g. for parsing LLM output).
|
|
28
|
+
*/
|
|
29
|
+
function isSerializableSchema(schema) {
|
|
30
|
+
return isStandardSchema(schema) && isStandardJsonSchema(schema);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
//#endregion
|
|
34
|
+
exports.isSerializableSchema = isSerializableSchema;
|
|
35
|
+
exports.isStandardJsonSchema = isStandardJsonSchema;
|
|
36
|
+
exports.isStandardSchema = isStandardSchema;
|
|
37
|
+
Object.defineProperty(exports, 'standard_schema_exports', {
|
|
38
|
+
enumerable: true,
|
|
39
|
+
get: function () {
|
|
40
|
+
return standard_schema_exports;
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
//# sourceMappingURL=standard_schema.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard_schema.cjs","names":[],"sources":["../../src/utils/standard_schema.ts"],"sourcesContent":["import { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * A schema that supports both runtime validation and JSON Schema generation. Any schema passed\n * to withStructuredOutput must satisfy both interfaces.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type SerializableSchema<Input = any, Output = Input> = StandardSchemaV1<\n Input,\n Output\n> &\n StandardJSONSchemaV1<Input, Output>;\n\n/**\n * Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate`\n * interface, indicating it can validate unknown values at runtime (e.g. for parsing LLM output).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isStandardSchema<Input = any, Output = Input>(\n schema: unknown\n): schema is StandardSchemaV1<Input, Output> {\n return (\n (typeof schema === \"object\" || typeof schema === \"function\") &&\n schema !== null &&\n \"~standard\" in schema &&\n typeof schema[\"~standard\"] === \"object\" &&\n schema[\"~standard\"] !== null &&\n \"validate\" in schema[\"~standard\"]\n );\n}\n\n/**\n * Type guard for Standard JSON Schema V1. Returns true if the value has a `~standard.jsonSchema`\n * interface, indicating it can be converted to a JSON Schema object (e.g. for sending as a tool\n * definition to an LLM).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isStandardJsonSchema<Input = any, Output = Input>(\n schema: unknown\n): schema is StandardJSONSchemaV1<Input, Output> {\n return (\n (typeof schema === \"object\" || typeof schema === \"function\") &&\n schema !== null &&\n \"~standard\" in schema &&\n typeof schema[\"~standard\"] === \"object\" &&\n schema[\"~standard\"] !== null &&\n \"jsonSchema\" in schema[\"~standard\"]\n );\n}\n\n/**\n * Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate` interface,\n * indicating it can validate unknown values at runtime (e.g. for parsing LLM output).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isSerializableSchema<Input = any, Output = Input>(\n schema: unknown\n): schema is SerializableSchema<Input, Output> {\n return isStandardSchema(schema) && isStandardJsonSchema(schema);\n}\n"],"mappings":";;;;;;;;;;;;;AAkBA,SAAgB,iBACd,QAC2C;AAC3C,SACG,OAAO,WAAW,YAAY,OAAO,WAAW,eACjD,WAAW,QACX,eAAe,UACf,OAAO,OAAO,iBAAiB,YAC/B,OAAO,iBAAiB,QACxB,cAAc,OAAO;;;;;;;AAUzB,SAAgB,qBACd,QAC+C;AAC/C,SACG,OAAO,WAAW,YAAY,OAAO,WAAW,eACjD,WAAW,QACX,eAAe,UACf,OAAO,OAAO,iBAAiB,YAC/B,OAAO,iBAAiB,QACxB,gBAAgB,OAAO;;;;;;AAS3B,SAAgB,qBACd,QAC6C;AAC7C,QAAO,iBAAiB,OAAO,IAAI,qBAAqB,OAAO"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
+
|
|
3
|
+
//#region src/utils/standard_schema.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* A schema that supports both runtime validation and JSON Schema generation. Any schema passed
|
|
6
|
+
* to withStructuredOutput must satisfy both interfaces.
|
|
7
|
+
*/
|
|
8
|
+
type SerializableSchema<Input = any, Output = Input> = StandardSchemaV1<Input, Output> & StandardJSONSchemaV1<Input, Output>;
|
|
9
|
+
/**
|
|
10
|
+
* Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate`
|
|
11
|
+
* interface, indicating it can validate unknown values at runtime (e.g. for parsing LLM output).
|
|
12
|
+
*/
|
|
13
|
+
declare function isStandardSchema<Input = any, Output = Input>(schema: unknown): schema is StandardSchemaV1<Input, Output>;
|
|
14
|
+
/**
|
|
15
|
+
* Type guard for Standard JSON Schema V1. Returns true if the value has a `~standard.jsonSchema`
|
|
16
|
+
* interface, indicating it can be converted to a JSON Schema object (e.g. for sending as a tool
|
|
17
|
+
* definition to an LLM).
|
|
18
|
+
*/
|
|
19
|
+
declare function isStandardJsonSchema<Input = any, Output = Input>(schema: unknown): schema is StandardJSONSchemaV1<Input, Output>;
|
|
20
|
+
/**
|
|
21
|
+
* Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate` interface,
|
|
22
|
+
* indicating it can validate unknown values at runtime (e.g. for parsing LLM output).
|
|
23
|
+
*/
|
|
24
|
+
declare function isSerializableSchema<Input = any, Output = Input>(schema: unknown): schema is SerializableSchema<Input, Output>;
|
|
25
|
+
//#endregion
|
|
26
|
+
export { SerializableSchema, isSerializableSchema, isStandardJsonSchema, isStandardSchema };
|
|
27
|
+
//# sourceMappingURL=standard_schema.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard_schema.d.cts","names":[],"sources":["../../src/utils/standard_schema.ts"],"mappings":";;;;;AAOA;;KAAY,kBAAA,uBAAyC,KAAA,IAAS,gBAAA,CAC5D,KAAA,EACA,MAAA,IAEA,oBAAA,CAAqB,KAAA,EAAO,MAAA;;;;;iBAOd,gBAAA,uBAAuC,KAAA,CAAA,CACrD,MAAA,YACC,MAAA,IAAU,gBAAA,CAAiB,KAAA,EAAO,MAAA;;;;;;iBAiBrB,oBAAA,uBAA2C,KAAA,CAAA,CACzD,MAAA,YACC,MAAA,IAAU,oBAAA,CAAqB,KAAA,EAAO,MAAA;;;;;iBAgBzB,oBAAA,uBAA2C,KAAA,CAAA,CACzD,MAAA,YACC,MAAA,IAAU,kBAAA,CAAmB,KAAA,EAAO,MAAA"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
+
|
|
3
|
+
//#region src/utils/standard_schema.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* A schema that supports both runtime validation and JSON Schema generation. Any schema passed
|
|
6
|
+
* to withStructuredOutput must satisfy both interfaces.
|
|
7
|
+
*/
|
|
8
|
+
type SerializableSchema<Input = any, Output = Input> = StandardSchemaV1<Input, Output> & StandardJSONSchemaV1<Input, Output>;
|
|
9
|
+
/**
|
|
10
|
+
* Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate`
|
|
11
|
+
* interface, indicating it can validate unknown values at runtime (e.g. for parsing LLM output).
|
|
12
|
+
*/
|
|
13
|
+
declare function isStandardSchema<Input = any, Output = Input>(schema: unknown): schema is StandardSchemaV1<Input, Output>;
|
|
14
|
+
/**
|
|
15
|
+
* Type guard for Standard JSON Schema V1. Returns true if the value has a `~standard.jsonSchema`
|
|
16
|
+
* interface, indicating it can be converted to a JSON Schema object (e.g. for sending as a tool
|
|
17
|
+
* definition to an LLM).
|
|
18
|
+
*/
|
|
19
|
+
declare function isStandardJsonSchema<Input = any, Output = Input>(schema: unknown): schema is StandardJSONSchemaV1<Input, Output>;
|
|
20
|
+
/**
|
|
21
|
+
* Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate` interface,
|
|
22
|
+
* indicating it can validate unknown values at runtime (e.g. for parsing LLM output).
|
|
23
|
+
*/
|
|
24
|
+
declare function isSerializableSchema<Input = any, Output = Input>(schema: unknown): schema is SerializableSchema<Input, Output>;
|
|
25
|
+
//#endregion
|
|
26
|
+
export { SerializableSchema, isSerializableSchema, isStandardJsonSchema, isStandardSchema };
|
|
27
|
+
//# sourceMappingURL=standard_schema.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard_schema.d.ts","names":[],"sources":["../../src/utils/standard_schema.ts"],"mappings":";;;;;AAOA;;KAAY,kBAAA,uBAAyC,KAAA,IAAS,gBAAA,CAC5D,KAAA,EACA,MAAA,IAEA,oBAAA,CAAqB,KAAA,EAAO,MAAA;;;;;iBAOd,gBAAA,uBAAuC,KAAA,CAAA,CACrD,MAAA,YACC,MAAA,IAAU,gBAAA,CAAiB,KAAA,EAAO,MAAA;;;;;;iBAiBrB,oBAAA,uBAA2C,KAAA,CAAA,CACzD,MAAA,YACC,MAAA,IAAU,oBAAA,CAAqB,KAAA,EAAO,MAAA;;;;;iBAgBzB,oBAAA,uBAA2C,KAAA,CAAA,CACzD,MAAA,YACC,MAAA,IAAU,kBAAA,CAAmB,KAAA,EAAO,MAAA"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { __exportAll } from "../_virtual/_rolldown/runtime.js";
|
|
2
|
+
|
|
3
|
+
//#region src/utils/standard_schema.ts
|
|
4
|
+
var standard_schema_exports = /* @__PURE__ */ __exportAll({
|
|
5
|
+
isSerializableSchema: () => isSerializableSchema,
|
|
6
|
+
isStandardJsonSchema: () => isStandardJsonSchema,
|
|
7
|
+
isStandardSchema: () => isStandardSchema
|
|
8
|
+
});
|
|
9
|
+
/**
|
|
10
|
+
* Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate`
|
|
11
|
+
* interface, indicating it can validate unknown values at runtime (e.g. for parsing LLM output).
|
|
12
|
+
*/
|
|
13
|
+
function isStandardSchema(schema) {
|
|
14
|
+
return (typeof schema === "object" || typeof schema === "function") && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "validate" in schema["~standard"];
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Type guard for Standard JSON Schema V1. Returns true if the value has a `~standard.jsonSchema`
|
|
18
|
+
* interface, indicating it can be converted to a JSON Schema object (e.g. for sending as a tool
|
|
19
|
+
* definition to an LLM).
|
|
20
|
+
*/
|
|
21
|
+
function isStandardJsonSchema(schema) {
|
|
22
|
+
return (typeof schema === "object" || typeof schema === "function") && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "jsonSchema" in schema["~standard"];
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate` interface,
|
|
26
|
+
* indicating it can validate unknown values at runtime (e.g. for parsing LLM output).
|
|
27
|
+
*/
|
|
28
|
+
function isSerializableSchema(schema) {
|
|
29
|
+
return isStandardSchema(schema) && isStandardJsonSchema(schema);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
//#endregion
|
|
33
|
+
export { isSerializableSchema, isStandardJsonSchema, isStandardSchema, standard_schema_exports };
|
|
34
|
+
//# sourceMappingURL=standard_schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard_schema.js","names":[],"sources":["../../src/utils/standard_schema.ts"],"sourcesContent":["import { StandardJSONSchemaV1, StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * A schema that supports both runtime validation and JSON Schema generation. Any schema passed\n * to withStructuredOutput must satisfy both interfaces.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type SerializableSchema<Input = any, Output = Input> = StandardSchemaV1<\n Input,\n Output\n> &\n StandardJSONSchemaV1<Input, Output>;\n\n/**\n * Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate`\n * interface, indicating it can validate unknown values at runtime (e.g. for parsing LLM output).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isStandardSchema<Input = any, Output = Input>(\n schema: unknown\n): schema is StandardSchemaV1<Input, Output> {\n return (\n (typeof schema === \"object\" || typeof schema === \"function\") &&\n schema !== null &&\n \"~standard\" in schema &&\n typeof schema[\"~standard\"] === \"object\" &&\n schema[\"~standard\"] !== null &&\n \"validate\" in schema[\"~standard\"]\n );\n}\n\n/**\n * Type guard for Standard JSON Schema V1. Returns true if the value has a `~standard.jsonSchema`\n * interface, indicating it can be converted to a JSON Schema object (e.g. for sending as a tool\n * definition to an LLM).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isStandardJsonSchema<Input = any, Output = Input>(\n schema: unknown\n): schema is StandardJSONSchemaV1<Input, Output> {\n return (\n (typeof schema === \"object\" || typeof schema === \"function\") &&\n schema !== null &&\n \"~standard\" in schema &&\n typeof schema[\"~standard\"] === \"object\" &&\n schema[\"~standard\"] !== null &&\n \"jsonSchema\" in schema[\"~standard\"]\n );\n}\n\n/**\n * Type guard for Standard Schema V1. Returns true if the value has a `~standard.validate` interface,\n * indicating it can validate unknown values at runtime (e.g. for parsing LLM output).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isSerializableSchema<Input = any, Output = Input>(\n schema: unknown\n): schema is SerializableSchema<Input, Output> {\n return isStandardSchema(schema) && isStandardJsonSchema(schema);\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,SAAgB,iBACd,QAC2C;AAC3C,SACG,OAAO,WAAW,YAAY,OAAO,WAAW,eACjD,WAAW,QACX,eAAe,UACf,OAAO,OAAO,iBAAiB,YAC/B,OAAO,iBAAiB,QACxB,cAAc,OAAO;;;;;;;AAUzB,SAAgB,qBACd,QAC+C;AAC/C,SACG,OAAO,WAAW,YAAY,OAAO,WAAW,eACjD,WAAW,QACX,eAAe,UACf,OAAO,OAAO,iBAAiB,YAC/B,OAAO,iBAAiB,QACxB,gBAAgB,OAAO;;;;;;AAS3B,SAAgB,qBACd,QAC6C;AAC7C,QAAO,iBAAiB,OAAO,IAAI,qBAAqB,OAAO"}
|