@langchain/core 1.0.0-alpha.3 → 1.0.0-alpha.4
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/README.md +3 -19
- package/dist/caches/base.cjs +2 -2
- package/dist/caches/base.cjs.map +1 -1
- package/dist/callbacks/base.d.ts.map +1 -1
- package/dist/document_loaders/langsmith.cjs +1 -1
- package/dist/document_loaders/langsmith.cjs.map +1 -1
- package/dist/document_loaders/langsmith.js +1 -1
- package/dist/document_loaders/langsmith.js.map +1 -1
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.d.cts +6 -6
- package/dist/embeddings.d.cts.map +1 -1
- package/dist/embeddings.d.ts +6 -6
- package/dist/embeddings.d.ts.map +1 -1
- package/dist/embeddings.js.map +1 -1
- package/dist/errors/index.cjs.map +1 -1
- package/dist/errors/index.js.map +1 -1
- package/dist/indexing/base.cjs +2 -2
- package/dist/indexing/base.cjs.map +1 -1
- package/dist/indexing/base.d.cts +0 -3
- package/dist/indexing/base.d.cts.map +1 -1
- package/dist/indexing/base.d.ts +0 -3
- package/dist/indexing/base.d.ts.map +1 -1
- package/dist/indexing/base.js +2 -2
- package/dist/indexing/base.js.map +1 -1
- package/dist/language_models/base.cjs +1 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.d.cts +3 -3
- package/dist/language_models/base.d.cts.map +1 -1
- package/dist/language_models/base.d.ts +3 -3
- 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.map +1 -1
- package/dist/language_models/chat_models.d.ts.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 +1 -5
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +3 -7
- 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.map +1 -1
- package/dist/load/serializable.d.cts +1 -3
- package/dist/load/serializable.d.cts.map +1 -1
- package/dist/load/serializable.d.ts +1 -3
- package/dist/load/serializable.d.ts.map +1 -1
- package/dist/load/serializable.js.map +1 -1
- package/dist/messages/ai.cjs +2 -2
- package/dist/messages/ai.cjs.map +1 -1
- package/dist/messages/ai.js +2 -2
- package/dist/messages/ai.js.map +1 -1
- package/dist/messages/base.cjs +5 -5
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.d.cts +1 -2
- package/dist/messages/base.d.cts.map +1 -1
- package/dist/messages/base.d.ts +1 -2
- package/dist/messages/base.d.ts.map +1 -1
- package/dist/messages/base.js +5 -5
- package/dist/messages/base.js.map +1 -1
- package/dist/messages/block_translators/utils.cjs +1 -1
- package/dist/messages/block_translators/utils.cjs.map +1 -1
- package/dist/messages/block_translators/utils.js +1 -1
- package/dist/messages/block_translators/utils.js.map +1 -1
- package/dist/messages/index.cjs +1 -1
- package/dist/messages/index.js +1 -1
- package/dist/messages/modifier.cjs +4 -1
- package/dist/messages/modifier.cjs.map +1 -1
- package/dist/messages/modifier.js +4 -1
- package/dist/messages/modifier.js.map +1 -1
- package/dist/messages/tool.cjs +7 -7
- package/dist/messages/tool.cjs.map +1 -1
- package/dist/messages/tool.js +7 -7
- package/dist/messages/tool.js.map +1 -1
- package/dist/messages/transformers.cjs +2 -2
- package/dist/messages/transformers.cjs.map +1 -1
- package/dist/messages/transformers.js +2 -2
- package/dist/messages/transformers.js.map +1 -1
- package/dist/messages/utils.cjs +5 -0
- package/dist/messages/utils.cjs.map +1 -1
- package/dist/messages/utils.js +5 -0
- package/dist/messages/utils.js.map +1 -1
- package/dist/output_parsers/list.cjs +1 -1
- package/dist/output_parsers/list.cjs.map +1 -1
- package/dist/output_parsers/list.js +1 -1
- package/dist/output_parsers/list.js.map +1 -1
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.d.cts +1 -1
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.d.ts +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs +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 +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.js.map +1 -1
- package/dist/output_parsers/structured.cjs +2 -1
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.js +2 -1
- package/dist/output_parsers/structured.js.map +1 -1
- package/dist/prompts/chat.cjs +3 -1
- package/dist/prompts/chat.cjs.map +1 -1
- package/dist/prompts/chat.d.cts +4 -12
- package/dist/prompts/chat.d.cts.map +1 -1
- package/dist/prompts/chat.d.ts +4 -12
- package/dist/prompts/chat.d.ts.map +1 -1
- package/dist/prompts/chat.js +3 -1
- package/dist/prompts/chat.js.map +1 -1
- package/dist/prompts/image.cjs.map +1 -1
- package/dist/prompts/image.d.cts +0 -2
- package/dist/prompts/image.d.cts.map +1 -1
- package/dist/prompts/image.d.ts +0 -2
- package/dist/prompts/image.d.ts.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.d.cts +4 -16
- package/dist/prompts/prompt.d.cts.map +1 -1
- package/dist/prompts/prompt.d.ts +4 -16
- package/dist/prompts/prompt.d.ts.map +1 -1
- package/dist/prompts/prompt.js.map +1 -1
- package/dist/prompts/structured.cjs.map +1 -1
- package/dist/prompts/structured.js.map +1 -1
- package/dist/prompts/template.cjs +4 -2
- package/dist/prompts/template.cjs.map +1 -1
- package/dist/prompts/template.js +4 -2
- package/dist/prompts/template.js.map +1 -1
- package/dist/runnables/base.cjs +6 -6
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.d.cts +0 -3
- package/dist/runnables/base.d.cts.map +1 -1
- package/dist/runnables/base.d.ts +0 -3
- package/dist/runnables/base.d.ts.map +1 -1
- package/dist/runnables/base.js +6 -6
- package/dist/runnables/base.js.map +1 -1
- package/dist/runnables/branch.cjs +2 -2
- package/dist/runnables/branch.cjs.map +1 -1
- package/dist/runnables/branch.js +2 -2
- package/dist/runnables/branch.js.map +1 -1
- package/dist/runnables/config.cjs.map +1 -1
- package/dist/runnables/config.js.map +1 -1
- package/dist/runnables/graph.cjs +1 -1
- package/dist/runnables/graph.cjs.map +1 -1
- package/dist/runnables/graph.js +1 -1
- package/dist/runnables/graph.js.map +1 -1
- package/dist/runnables/graph_mermaid.cjs +26 -3
- package/dist/runnables/graph_mermaid.cjs.map +1 -1
- package/dist/runnables/graph_mermaid.js +26 -3
- package/dist/runnables/graph_mermaid.js.map +1 -1
- package/dist/runnables/remote.cjs.map +1 -1
- package/dist/runnables/remote.js.map +1 -1
- package/dist/runnables/types.d.cts +0 -1
- package/dist/runnables/types.d.cts.map +1 -1
- package/dist/runnables/types.d.ts +0 -1
- package/dist/runnables/types.d.ts.map +1 -1
- package/dist/singletons/async_local_storage/context.cjs.map +1 -1
- package/dist/singletons/async_local_storage/context.d.cts +0 -1
- package/dist/singletons/async_local_storage/context.d.cts.map +1 -1
- package/dist/singletons/async_local_storage/context.d.ts +0 -1
- package/dist/singletons/async_local_storage/context.d.ts.map +1 -1
- package/dist/singletons/async_local_storage/context.js.map +1 -1
- package/dist/singletons/callbacks.cjs.map +1 -1
- package/dist/singletons/callbacks.js.map +1 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.d.cts +2 -2
- package/dist/tools/index.d.cts.map +1 -1
- package/dist/tools/index.d.ts +2 -2
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/types.d.cts +5 -5
- package/dist/tools/types.d.cts.map +1 -1
- package/dist/tools/types.d.ts +5 -5
- package/dist/tools/types.d.ts.map +1 -1
- package/dist/tracers/base.cjs.map +1 -1
- package/dist/tracers/base.js.map +1 -1
- package/dist/tracers/console.cjs +1 -1
- package/dist/tracers/console.cjs.map +1 -1
- package/dist/tracers/console.js +1 -1
- package/dist/tracers/console.js.map +1 -1
- package/dist/tracers/event_stream.cjs +1 -1
- package/dist/tracers/event_stream.cjs.map +1 -1
- package/dist/tracers/event_stream.d.cts +0 -1
- package/dist/tracers/event_stream.d.cts.map +1 -1
- package/dist/tracers/event_stream.d.ts +0 -1
- package/dist/tracers/event_stream.d.ts.map +1 -1
- package/dist/tracers/event_stream.js +1 -1
- package/dist/tracers/event_stream.js.map +1 -1
- package/dist/tracers/log_stream.cjs.map +1 -1
- package/dist/tracers/log_stream.js.map +1 -1
- package/dist/tracers/tracer_langchain.cjs.map +1 -1
- package/dist/tracers/tracer_langchain.js.map +1 -1
- package/dist/utils/chunk_array.cjs.map +1 -1
- package/dist/utils/chunk_array.js.map +1 -1
- package/dist/utils/env.cjs +1 -1
- package/dist/utils/env.cjs.map +1 -1
- package/dist/utils/env.js +1 -1
- package/dist/utils/env.js.map +1 -1
- package/dist/utils/event_source_parse.cjs.map +1 -1
- package/dist/utils/event_source_parse.d.cts.map +1 -1
- package/dist/utils/event_source_parse.d.ts.map +1 -1
- package/dist/utils/event_source_parse.js.map +1 -1
- package/dist/utils/hash.cjs +3 -8
- package/dist/utils/hash.cjs.map +1 -1
- package/dist/utils/hash.d.cts +1 -2
- package/dist/utils/hash.d.cts.map +1 -1
- package/dist/utils/hash.d.ts +1 -2
- package/dist/utils/hash.d.ts.map +1 -1
- package/dist/utils/hash.js +2 -6
- package/dist/utils/hash.js.map +1 -1
- package/dist/utils/js-sha256/hash.cjs +0 -9
- package/dist/utils/js-sha256/hash.cjs.map +1 -1
- package/dist/utils/js-sha256/hash.js +1 -5
- package/dist/utils/js-sha256/hash.js.map +1 -1
- package/dist/utils/json.cjs +2 -2
- package/dist/utils/json.cjs.map +1 -1
- package/dist/utils/json.js +2 -2
- package/dist/utils/json.js.map +1 -1
- package/dist/utils/json_schema.cjs +3 -2
- package/dist/utils/json_schema.cjs.map +1 -1
- package/dist/utils/json_schema.d.cts +8 -4
- package/dist/utils/json_schema.d.cts.map +1 -1
- package/dist/utils/json_schema.d.ts +8 -4
- package/dist/utils/json_schema.d.ts.map +1 -1
- package/dist/utils/json_schema.js +2 -1
- package/dist/utils/json_schema.js.map +1 -1
- package/dist/utils/stream.cjs.map +1 -1
- package/dist/utils/stream.js.map +1 -1
- package/dist/utils/testing/index.cjs.map +1 -1
- package/dist/utils/testing/index.d.cts +4 -9
- package/dist/utils/testing/index.d.cts.map +1 -1
- package/dist/utils/testing/index.d.ts +4 -9
- package/dist/utils/testing/index.d.ts.map +1 -1
- package/dist/utils/testing/index.js.map +1 -1
- package/dist/utils/zod-to-json-schema/Options.cjs +40 -0
- package/dist/utils/zod-to-json-schema/Options.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/Options.js +37 -0
- package/dist/utils/zod-to-json-schema/Options.js.map +1 -0
- package/dist/utils/zod-to-json-schema/Refs.cjs +30 -0
- package/dist/utils/zod-to-json-schema/Refs.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/Refs.js +30 -0
- package/dist/utils/zod-to-json-schema/Refs.js.map +1 -0
- package/dist/utils/zod-to-json-schema/errorMessages.cjs +18 -0
- package/dist/utils/zod-to-json-schema/errorMessages.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/errorMessages.d.cts +11 -0
- package/dist/utils/zod-to-json-schema/errorMessages.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/errorMessages.d.ts +11 -0
- package/dist/utils/zod-to-json-schema/errorMessages.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/errorMessages.js +16 -0
- package/dist/utils/zod-to-json-schema/errorMessages.js.map +1 -0
- package/dist/utils/zod-to-json-schema/getRelativePath.cjs +11 -0
- package/dist/utils/zod-to-json-schema/getRelativePath.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/getRelativePath.js +10 -0
- package/dist/utils/zod-to-json-schema/getRelativePath.js.map +1 -0
- package/dist/utils/zod-to-json-schema/index.cjs +37 -0
- package/dist/utils/zod-to-json-schema/index.js +37 -0
- package/dist/utils/zod-to-json-schema/parseDef.cjs +57 -0
- package/dist/utils/zod-to-json-schema/parseDef.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parseDef.js +57 -0
- package/dist/utils/zod-to-json-schema/parseDef.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parseTypes.d.cts +38 -0
- package/dist/utils/zod-to-json-schema/parseTypes.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parseTypes.d.ts +38 -0
- package/dist/utils/zod-to-json-schema/parseTypes.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/any.cjs +17 -0
- package/dist/utils/zod-to-json-schema/parsers/any.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/any.d.cts +7 -0
- package/dist/utils/zod-to-json-schema/parsers/any.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/any.d.ts +7 -0
- package/dist/utils/zod-to-json-schema/parsers/any.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/any.js +17 -0
- package/dist/utils/zod-to-json-schema/parsers/any.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/array.cjs +24 -0
- package/dist/utils/zod-to-json-schema/parsers/array.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/array.d.cts +14 -0
- package/dist/utils/zod-to-json-schema/parsers/array.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/array.d.ts +15 -0
- package/dist/utils/zod-to-json-schema/parsers/array.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/array.js +23 -0
- package/dist/utils/zod-to-json-schema/parsers/array.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/bigint.cjs +36 -0
- package/dist/utils/zod-to-json-schema/parsers/bigint.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/bigint.d.cts +16 -0
- package/dist/utils/zod-to-json-schema/parsers/bigint.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/bigint.d.ts +17 -0
- package/dist/utils/zod-to-json-schema/parsers/bigint.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/bigint.js +36 -0
- package/dist/utils/zod-to-json-schema/parsers/bigint.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/boolean.cjs +9 -0
- package/dist/utils/zod-to-json-schema/parsers/boolean.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/boolean.d.cts +7 -0
- package/dist/utils/zod-to-json-schema/parsers/boolean.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/boolean.d.ts +7 -0
- package/dist/utils/zod-to-json-schema/parsers/boolean.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/boolean.js +8 -0
- package/dist/utils/zod-to-json-schema/parsers/boolean.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/branded.cjs +10 -0
- package/dist/utils/zod-to-json-schema/parsers/branded.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/branded.js +10 -0
- package/dist/utils/zod-to-json-schema/parsers/branded.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/catch.cjs +10 -0
- package/dist/utils/zod-to-json-schema/parsers/catch.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/catch.js +10 -0
- package/dist/utils/zod-to-json-schema/parsers/catch.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/date.cjs +39 -0
- package/dist/utils/zod-to-json-schema/parsers/date.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/date.d.cts +17 -0
- package/dist/utils/zod-to-json-schema/parsers/date.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/date.d.ts +17 -0
- package/dist/utils/zod-to-json-schema/parsers/date.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/date.js +39 -0
- package/dist/utils/zod-to-json-schema/parsers/date.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/default.cjs +13 -0
- package/dist/utils/zod-to-json-schema/parsers/default.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/default.js +13 -0
- package/dist/utils/zod-to-json-schema/parsers/default.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/effects.cjs +11 -0
- package/dist/utils/zod-to-json-schema/parsers/effects.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/effects.js +11 -0
- package/dist/utils/zod-to-json-schema/parsers/effects.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/enum.cjs +12 -0
- package/dist/utils/zod-to-json-schema/parsers/enum.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/enum.d.cts +8 -0
- package/dist/utils/zod-to-json-schema/parsers/enum.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/enum.d.ts +10 -0
- package/dist/utils/zod-to-json-schema/parsers/enum.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/enum.js +11 -0
- package/dist/utils/zod-to-json-schema/parsers/enum.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/intersection.cjs +47 -0
- package/dist/utils/zod-to-json-schema/parsers/intersection.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/intersection.d.cts +10 -0
- package/dist/utils/zod-to-json-schema/parsers/intersection.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/intersection.d.ts +11 -0
- package/dist/utils/zod-to-json-schema/parsers/intersection.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/intersection.js +47 -0
- package/dist/utils/zod-to-json-schema/parsers/intersection.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/literal.cjs +18 -0
- package/dist/utils/zod-to-json-schema/parsers/literal.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/literal.d.cts +11 -0
- package/dist/utils/zod-to-json-schema/parsers/literal.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/literal.d.ts +12 -0
- package/dist/utils/zod-to-json-schema/parsers/literal.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/literal.js +17 -0
- package/dist/utils/zod-to-json-schema/parsers/literal.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/map.cjs +40 -0
- package/dist/utils/zod-to-json-schema/parsers/map.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/map.d.cts +17 -0
- package/dist/utils/zod-to-json-schema/parsers/map.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/map.d.ts +17 -0
- package/dist/utils/zod-to-json-schema/parsers/map.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/map.js +40 -0
- package/dist/utils/zod-to-json-schema/parsers/map.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/nativeEnum.cjs +18 -0
- package/dist/utils/zod-to-json-schema/parsers/nativeEnum.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/nativeEnum.d.cts +8 -0
- package/dist/utils/zod-to-json-schema/parsers/nativeEnum.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/nativeEnum.d.ts +10 -0
- package/dist/utils/zod-to-json-schema/parsers/nativeEnum.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/nativeEnum.js +17 -0
- package/dist/utils/zod-to-json-schema/parsers/nativeEnum.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/never.cjs +13 -0
- package/dist/utils/zod-to-json-schema/parsers/never.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/never.d.cts +9 -0
- package/dist/utils/zod-to-json-schema/parsers/never.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/never.d.ts +9 -0
- package/dist/utils/zod-to-json-schema/parsers/never.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/never.js +13 -0
- package/dist/utils/zod-to-json-schema/parsers/never.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/null.cjs +12 -0
- package/dist/utils/zod-to-json-schema/parsers/null.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/null.d.cts +7 -0
- package/dist/utils/zod-to-json-schema/parsers/null.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/null.d.ts +7 -0
- package/dist/utils/zod-to-json-schema/parsers/null.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/null.js +11 -0
- package/dist/utils/zod-to-json-schema/parsers/null.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/nullable.cjs +46 -0
- package/dist/utils/zod-to-json-schema/parsers/nullable.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/nullable.d.cts +12 -0
- package/dist/utils/zod-to-json-schema/parsers/nullable.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/nullable.d.ts +13 -0
- package/dist/utils/zod-to-json-schema/parsers/nullable.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/nullable.js +46 -0
- package/dist/utils/zod-to-json-schema/parsers/nullable.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/number.cjs +37 -0
- package/dist/utils/zod-to-json-schema/parsers/number.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/number.d.cts +15 -0
- package/dist/utils/zod-to-json-schema/parsers/number.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/number.d.ts +16 -0
- package/dist/utils/zod-to-json-schema/parsers/number.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/number.js +37 -0
- package/dist/utils/zod-to-json-schema/parsers/number.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/object.cjs +64 -0
- package/dist/utils/zod-to-json-schema/parsers/object.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/object.d.cts +12 -0
- package/dist/utils/zod-to-json-schema/parsers/object.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/object.d.ts +13 -0
- package/dist/utils/zod-to-json-schema/parsers/object.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/object.js +64 -0
- package/dist/utils/zod-to-json-schema/parsers/object.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/optional.cjs +20 -0
- package/dist/utils/zod-to-json-schema/parsers/optional.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/optional.js +20 -0
- package/dist/utils/zod-to-json-schema/parsers/optional.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/pipeline.cjs +28 -0
- package/dist/utils/zod-to-json-schema/parsers/pipeline.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/pipeline.js +28 -0
- package/dist/utils/zod-to-json-schema/parsers/pipeline.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/promise.cjs +10 -0
- package/dist/utils/zod-to-json-schema/parsers/promise.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/promise.js +10 -0
- package/dist/utils/zod-to-json-schema/parsers/promise.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/readonly.cjs +10 -0
- package/dist/utils/zod-to-json-schema/parsers/readonly.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/readonly.js +10 -0
- package/dist/utils/zod-to-json-schema/parsers/readonly.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/record.cjs +57 -0
- package/dist/utils/zod-to-json-schema/parsers/record.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/record.d.cts +14 -0
- package/dist/utils/zod-to-json-schema/parsers/record.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/record.d.ts +15 -0
- package/dist/utils/zod-to-json-schema/parsers/record.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/record.js +56 -0
- package/dist/utils/zod-to-json-schema/parsers/record.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/set.cjs +22 -0
- package/dist/utils/zod-to-json-schema/parsers/set.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/set.d.cts +15 -0
- package/dist/utils/zod-to-json-schema/parsers/set.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/set.d.ts +16 -0
- package/dist/utils/zod-to-json-schema/parsers/set.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/set.js +22 -0
- package/dist/utils/zod-to-json-schema/parsers/set.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/string.cjs +255 -0
- package/dist/utils/zod-to-json-schema/parsers/string.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/string.d.cts +28 -0
- package/dist/utils/zod-to-json-schema/parsers/string.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/string.d.ts +29 -0
- package/dist/utils/zod-to-json-schema/parsers/string.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/string.js +254 -0
- package/dist/utils/zod-to-json-schema/parsers/string.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/tuple.cjs +38 -0
- package/dist/utils/zod-to-json-schema/parsers/tuple.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/tuple.d.cts +15 -0
- package/dist/utils/zod-to-json-schema/parsers/tuple.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/tuple.d.ts +16 -0
- package/dist/utils/zod-to-json-schema/parsers/tuple.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/tuple.js +38 -0
- package/dist/utils/zod-to-json-schema/parsers/tuple.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/undefined.cjs +10 -0
- package/dist/utils/zod-to-json-schema/parsers/undefined.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/undefined.d.cts +9 -0
- package/dist/utils/zod-to-json-schema/parsers/undefined.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/undefined.d.ts +9 -0
- package/dist/utils/zod-to-json-schema/parsers/undefined.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/undefined.js +10 -0
- package/dist/utils/zod-to-json-schema/parsers/undefined.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/union.cjs +67 -0
- package/dist/utils/zod-to-json-schema/parsers/union.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/union.d.cts +24 -0
- package/dist/utils/zod-to-json-schema/parsers/union.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/union.d.ts +25 -0
- package/dist/utils/zod-to-json-schema/parsers/union.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/union.js +66 -0
- package/dist/utils/zod-to-json-schema/parsers/union.js.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/unknown.cjs +10 -0
- package/dist/utils/zod-to-json-schema/parsers/unknown.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/unknown.d.cts +7 -0
- package/dist/utils/zod-to-json-schema/parsers/unknown.d.cts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/unknown.d.ts +7 -0
- package/dist/utils/zod-to-json-schema/parsers/unknown.d.ts.map +1 -0
- package/dist/utils/zod-to-json-schema/parsers/unknown.js +10 -0
- package/dist/utils/zod-to-json-schema/parsers/unknown.js.map +1 -0
- package/dist/utils/zod-to-json-schema/selectParser.cjs +81 -0
- package/dist/utils/zod-to-json-schema/selectParser.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/selectParser.js +80 -0
- package/dist/utils/zod-to-json-schema/selectParser.js.map +1 -0
- package/dist/utils/zod-to-json-schema/zodToJsonSchema.cjs +70 -0
- package/dist/utils/zod-to-json-schema/zodToJsonSchema.cjs.map +1 -0
- package/dist/utils/zod-to-json-schema/zodToJsonSchema.js +70 -0
- package/dist/utils/zod-to-json-schema/zodToJsonSchema.js.map +1 -0
- package/package.json +7 -36
- package/dist/utils/js-sha1/hash.cjs +0 -291
- package/dist/utils/js-sha1/hash.cjs.map +0 -1
- package/dist/utils/js-sha1/hash.d.cts +0 -9
- package/dist/utils/js-sha1/hash.d.cts.map +0 -1
- package/dist/utils/js-sha1/hash.d.ts +0 -9
- package/dist/utils/js-sha1/hash.d.ts.map +0 -1
- package/dist/utils/js-sha1/hash.js +0 -284
- package/dist/utils/js-sha1/hash.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ChatGeneration, Generation } from "../../outputs.js";
|
|
2
2
|
import { Operation } from "../../utils/fast-json-patch/src/core.js";
|
|
3
|
-
import { JsonSchema7ObjectType } from "../../utils/
|
|
3
|
+
import { JsonSchema7ObjectType } from "../../utils/zod-to-json-schema/parsers/object.js";
|
|
4
4
|
import { BaseLLMOutputParser } from "../base.js";
|
|
5
5
|
import { BaseCumulativeTransformOutputParser, BaseCumulativeTransformOutputParserInput } from "../transform.js";
|
|
6
6
|
import { Optional } from "../../types/type-utils.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_output_tools_parsers.cjs","names":["rawToolCall: Record<string, any>","options?: { returnId?: boolean; partial?: boolean }","parsePartialJson","e: any","OutputParserException","parsedToolCall: ToolCall","toolCall: ToolCall","errorMsg?: string","BaseCumulativeTransformOutputParser","fields?: JsonOutputToolsParserParams","generations: ChatGeneration[]","generations: ChatGenerationChunk[] | ChatGeneration[]","isAIMessage","rawToolCall: Record<string, unknown>","backwardsCompatibleToolCall: ParsedToolCall","params:\n | JsonOutputKeyToolsParserParamsV3<T>\n | JsonOutputKeyToolsParserParamsV4<T>\n | JsonOutputKeyToolsParserParamsInterop<T>","result: unknown","interopSafeParseAsync","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 (e) {\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,eAAeC,8BAAiB,YAAY,SAAS,aAAa,KAAK;CACxE,SAAQ,GAAG;AACV,SAAO;CACR;KAED,KAAI;EACF,eAAe,KAAK,MAAM,YAAY,SAAS,UAAU;CAE1D,SAAQC,GAAQ;AACf,QAAM,IAAIC,mCACR;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,iCAAiCC,UAAoB;AACnE,KAAI,SAAS,OAAO,OAClB,OAAM,IAAI,MAAM,CAAC,8CAA8C,CAAC;AAElE,QAAO;EACL,IAAI,SAAS;EACb,MAAM;EACN,UAAU;GACR,MAAM,SAAS;GACf,WAAW,KAAK,UAAU,SAAS,KAAK;EACzC;CACF;AACF;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AgB,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.cjs","names":["rawToolCall: Record<string, any>","options?: { returnId?: boolean; partial?: boolean }","parsePartialJson","e: any","OutputParserException","parsedToolCall: ToolCall","toolCall: ToolCall","errorMsg?: string","BaseCumulativeTransformOutputParser","fields?: JsonOutputToolsParserParams","generations: ChatGeneration[]","generations: ChatGenerationChunk[] | ChatGeneration[]","isAIMessage","rawToolCall: Record<string, unknown>","backwardsCompatibleToolCall: ParsedToolCall","params:\n | JsonOutputKeyToolsParserParamsV3<T>\n | JsonOutputKeyToolsParserParamsV4<T>\n | JsonOutputKeyToolsParserParamsInterop<T>","result: unknown","interopSafeParseAsync","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,eAAeC,8BAAiB,YAAY,SAAS,aAAa,KAAK;CACxE,QAAO;AACN,SAAO;CACR;KAED,KAAI;EACF,eAAe,KAAK,MAAM,YAAY,SAAS,UAAU;CAE1D,SAAQC,GAAQ;AACf,QAAM,IAAIC,mCACR;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,iCAAiCC,UAAoB;AACnE,KAAI,SAAS,OAAO,OAClB,OAAM,IAAI,MAAM,CAAC,8CAA8C,CAAC;AAElE,QAAO;EACL,IAAI,SAAS;EACb,MAAM;EACN,UAAU;GACR,MAAM,SAAS;GACf,WAAW,KAAK,UAAU,SAAS,KAAK;EACzC;CACF;AACF;AAED,SAAgB,oBAEdN,aACAO,UACiB;AACjB,QAAO;EACL,MAAM,YAAY,UAAU;EAC5B,MAAM,YAAY,UAAU;EAC5B,IAAI,YAAY;EAChB,OAAO;EACP,MAAM;CACP;AACF;;;;AAKD,IAAa,wBAAb,cAEUC,sDAAuC;CAC/C,OAAO,UAAU;AACf,SAAO;CACR;CAED,WAAW;CAEX,eAAe;EAAC;EAAa;EAAkB;CAAe;CAE9D,kBAAkB;CAElB,YAAYC,QAA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
|
-
{"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 (e) {\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,SAAQ,GAAG;AACV,SAAO;CACR;KAED,KAAI;EACF,eAAe,KAAK,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AU,gBAAgB,OAAO,OAAO,EAAE,EAC7D,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;A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K,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"}
|
|
@@ -69,7 +69,8 @@ ${JSON.stringify(require_utils_json_schema.toJsonSchema(this.schema))}
|
|
|
69
69
|
*/
|
|
70
70
|
async parse(text) {
|
|
71
71
|
try {
|
|
72
|
-
const
|
|
72
|
+
const trimmedText = text.trim();
|
|
73
|
+
const json = trimmedText.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1] || trimmedText.match(/```json\s*([\s\S]*?)```/)?.[1] || trimmedText;
|
|
73
74
|
const escapedJson = json.replace(/"([^"\\]*(\\.[^"\\]*)*)"/g, (_match, capturedGroup) => {
|
|
74
75
|
const escapedInsideQuotes = capturedGroup.replace(/\n/g, "\\n");
|
|
75
76
|
return `"${escapedInsideQuotes}"`;
|
|
@@ -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 json = text.includes(\"```\")\n ? text.trim().split(/```(?:json)?/)[1]\n : text.trim();\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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AM,KAAK,qBAAqB,GAAG,OAAO,CAAC,CAChD,KAAK,CAAC,EAAE,EAAE,IAAI,OAAO,SAAS,EAAE,EAAE,CAAC;AAGxC,QAAM,IAAI,MAAM;CACjB;CAED,OAAO,cAAwCX,QAAW;AACxD,SAAO,IAAI,KAAQ;CACpB;CAED,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,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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G,OAAO,cAAc,YAAY;EAC5C;AAED,MAAI,WAAW,OACb,QAAO,OAAO,MACX,IAAI,CAAC,MAAM,KAAK,qBAAqB,GAAG,OAAO,CAAC,CAChD,KAAK,CAAC,EAAE,EAAE,IAAI,OAAO,SAAS,EAAE,EAAE,CAAC;AAGxC,QAAM,IAAI,MAAM;CACjB;CAED,OAAO,cAAwCX,QAAW;AACxD,SAAO,IAAI,KAAQ;CACpB;CAED,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,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"}
|
|
@@ -68,7 +68,8 @@ ${JSON.stringify(toJsonSchema(this.schema))}
|
|
|
68
68
|
*/
|
|
69
69
|
async parse(text) {
|
|
70
70
|
try {
|
|
71
|
-
const
|
|
71
|
+
const trimmedText = text.trim();
|
|
72
|
+
const json = trimmedText.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1] || trimmedText.match(/```json\s*([\s\S]*?)```/)?.[1] || trimmedText;
|
|
72
73
|
const escapedJson = json.replace(/"([^"\\]*(\\.[^"\\]*)*)"/g, (_match, capturedGroup) => {
|
|
73
74
|
const escapedInsideQuotes = capturedGroup.replace(/\n/g, "\\n");
|
|
74
75
|
return `"${escapedInsideQuotes}"`;
|
|
@@ -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 json = text.includes(\"```\")\n ? text.trim().split(/```(?:json)?/)[1]\n : text.trim();\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.structured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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.structured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K,sBAAsB,uBAAuB;CAC1D;AACF"}
|
package/dist/prompts/chat.cjs
CHANGED
|
@@ -478,7 +478,9 @@ var ChatPromptTemplate = class ChatPromptTemplate extends BaseChatPromptTemplate
|
|
|
478
478
|
let resultMessages = [];
|
|
479
479
|
for (const promptMessage of this.promptMessages) if (promptMessage instanceof require_base.BaseMessage) resultMessages.push(await this._parseImagePrompts(promptMessage, allValues));
|
|
480
480
|
else {
|
|
481
|
-
|
|
481
|
+
let inputValues;
|
|
482
|
+
if (this.templateFormat === "mustache") inputValues = { ...allValues };
|
|
483
|
+
else inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => {
|
|
482
484
|
if (!(inputVariable in allValues) && !(isMessagesPlaceholder(promptMessage) && promptMessage.optional)) {
|
|
483
485
|
const error = require_index.addLangChainErrorFields(/* @__PURE__ */ new Error(`Missing value for input variable \`${inputVariable.toString()}\``), "INVALID_PROMPT_INPUT");
|
|
484
486
|
throw error;
|