@langchain/core 1.1.9 → 1.1.11-dev-1767748783694
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/documents/document.cjs.map +1 -1
- package/dist/documents/document.js.map +1 -1
- package/dist/documents/transformers.cjs.map +1 -1
- package/dist/documents/transformers.js.map +1 -1
- package/dist/example_selectors/conditional.cjs.map +1 -1
- package/dist/example_selectors/conditional.js.map +1 -1
- package/dist/example_selectors/semantic_similarity.cjs.map +1 -1
- package/dist/example_selectors/semantic_similarity.js.map +1 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.js.map +1 -1
- package/dist/language_models/chat_models.cjs.map +1 -1
- package/dist/language_models/chat_models.js.map +1 -1
- package/dist/language_models/llms.cjs.map +1 -1
- package/dist/language_models/llms.js.map +1 -1
- package/dist/load/import_map.cjs +11 -11
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +11 -11
- package/dist/load/import_map.js.map +1 -1
- package/dist/load/index.cjs.map +1 -1
- package/dist/load/index.js.map +1 -1
- package/dist/load/serializable.cjs +3 -3
- package/dist/load/serializable.cjs.map +1 -1
- package/dist/load/serializable.js +3 -3
- package/dist/load/serializable.js.map +1 -1
- package/dist/load/validation.cjs +13 -7
- package/dist/load/validation.cjs.map +1 -1
- package/dist/load/validation.js +13 -7
- package/dist/load/validation.js.map +1 -1
- package/dist/messages/ai.cjs.map +1 -1
- package/dist/messages/ai.js.map +1 -1
- package/dist/messages/base.cjs +3 -1
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.d.cts +1 -1
- package/dist/messages/base.d.cts.map +1 -1
- package/dist/messages/base.d.ts +1 -1
- package/dist/messages/base.d.ts.map +1 -1
- package/dist/messages/base.js +3 -1
- package/dist/messages/base.js.map +1 -1
- package/dist/messages/chat.cjs.map +1 -1
- package/dist/messages/chat.js.map +1 -1
- package/dist/messages/content/data.cjs.map +1 -1
- package/dist/messages/content/data.js.map +1 -1
- package/dist/messages/content/index.cjs.map +1 -1
- package/dist/messages/content/index.js.map +1 -1
- package/dist/messages/content/tools.cjs.map +1 -1
- package/dist/messages/content/tools.js.map +1 -1
- package/dist/messages/function.cjs.map +1 -1
- package/dist/messages/function.js.map +1 -1
- package/dist/messages/human.cjs.map +1 -1
- package/dist/messages/human.js.map +1 -1
- package/dist/messages/message.cjs.map +1 -1
- package/dist/messages/message.js.map +1 -1
- package/dist/messages/metadata.cjs +1 -1
- package/dist/messages/metadata.cjs.map +1 -1
- package/dist/messages/metadata.js +1 -1
- package/dist/messages/metadata.js.map +1 -1
- package/dist/messages/modifier.cjs.map +1 -1
- package/dist/messages/modifier.js.map +1 -1
- package/dist/messages/system.cjs.map +1 -1
- package/dist/messages/system.js.map +1 -1
- package/dist/messages/tool.cjs.map +1 -1
- package/dist/messages/tool.js.map +1 -1
- package/dist/messages/utils.cjs.map +1 -1
- package/dist/messages/utils.js.map +1 -1
- package/dist/output_parsers/base.cjs.map +1 -1
- package/dist/output_parsers/base.js.map +1 -1
- package/dist/output_parsers/index.cjs +1 -1
- package/dist/output_parsers/index.js +1 -1
- package/dist/output_parsers/json.cjs.map +1 -1
- package/dist/output_parsers/json.js.map +1 -1
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.cjs.map +1 -1
- package/dist/output_parsers/openai_functions/json_output_functions_parsers.js.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.js.map +1 -1
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.js.map +1 -1
- package/dist/output_parsers/transform.cjs.map +1 -1
- package/dist/output_parsers/transform.js.map +1 -1
- package/dist/prompts/base.cjs.map +1 -1
- package/dist/prompts/base.js.map +1 -1
- package/dist/prompts/chat.cjs.map +1 -1
- package/dist/prompts/chat.js.map +1 -1
- package/dist/prompts/dict.cjs.map +1 -1
- package/dist/prompts/dict.js.map +1 -1
- package/dist/prompts/few_shot.cjs.map +1 -1
- package/dist/prompts/few_shot.js.map +1 -1
- package/dist/prompts/image.cjs.map +1 -1
- package/dist/prompts/image.js.map +1 -1
- package/dist/prompts/pipeline.cjs.map +1 -1
- package/dist/prompts/pipeline.js.map +1 -1
- package/dist/prompts/prompt.cjs.map +1 -1
- package/dist/prompts/prompt.js.map +1 -1
- package/dist/prompts/string.cjs.map +1 -1
- package/dist/prompts/string.js.map +1 -1
- package/dist/prompts/structured.cjs.map +1 -1
- package/dist/prompts/structured.js.map +1 -1
- package/dist/prompts/template.cjs +1 -4
- package/dist/prompts/template.cjs.map +1 -1
- package/dist/prompts/template.js +1 -4
- package/dist/prompts/template.js.map +1 -1
- package/dist/retrievers/index.cjs.map +1 -1
- package/dist/retrievers/index.js.map +1 -1
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.js.map +1 -1
- package/dist/runnables/branch.cjs.map +1 -1
- package/dist/runnables/branch.js.map +1 -1
- package/dist/runnables/history.cjs.map +1 -1
- package/dist/runnables/history.js.map +1 -1
- package/dist/runnables/passthrough.cjs.map +1 -1
- package/dist/runnables/passthrough.js.map +1 -1
- package/dist/runnables/router.cjs.map +1 -1
- package/dist/runnables/router.js.map +1 -1
- package/dist/singletons/callbacks.cjs.map +1 -1
- package/dist/singletons/callbacks.js.map +1 -1
- package/dist/structured_query/base.cjs.map +1 -1
- package/dist/structured_query/base.js.map +1 -1
- package/dist/structured_query/ir.cjs.map +1 -1
- package/dist/structured_query/ir.js.map +1 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.js.map +1 -1
- package/dist/utils/async_caller.cjs.map +1 -1
- package/dist/utils/async_caller.js.map +1 -1
- package/dist/utils/stream.cjs.map +1 -1
- package/dist/utils/stream.js.map +1 -1
- package/dist/utils/testing/chat_models.cjs.map +1 -1
- package/dist/utils/testing/chat_models.js.map +1 -1
- package/dist/utils/testing/tools.cjs.map +1 -1
- package/dist/utils/testing/tools.js.map +1 -1
- package/dist/utils/types/zod.cjs.map +1 -1
- package/dist/utils/types/zod.js.map +1 -1
- package/dist/vectorstores.cjs.map +1 -1
- package/dist/vectorstores.d.cts.map +1 -1
- package/dist/vectorstores.js.map +1 -1
- package/package.json +2 -2
- package/agents.cjs +0 -1
- package/agents.d.cts +0 -1
- package/agents.d.ts +0 -1
- package/agents.js +0 -1
- package/caches.cjs +0 -1
- package/caches.d.cts +0 -1
- package/caches.d.ts +0 -1
- package/caches.js +0 -1
- package/callbacks/base.cjs +0 -1
- package/callbacks/base.d.cts +0 -1
- package/callbacks/base.d.ts +0 -1
- package/callbacks/base.js +0 -1
- package/callbacks/dispatch/web.cjs +0 -1
- package/callbacks/dispatch/web.d.cts +0 -1
- package/callbacks/dispatch/web.d.ts +0 -1
- package/callbacks/dispatch/web.js +0 -1
- package/callbacks/dispatch.cjs +0 -1
- package/callbacks/dispatch.d.cts +0 -1
- package/callbacks/dispatch.d.ts +0 -1
- package/callbacks/dispatch.js +0 -1
- package/callbacks/manager.cjs +0 -1
- package/callbacks/manager.d.cts +0 -1
- package/callbacks/manager.d.ts +0 -1
- package/callbacks/manager.js +0 -1
- package/callbacks/promises.cjs +0 -1
- package/callbacks/promises.d.cts +0 -1
- package/callbacks/promises.d.ts +0 -1
- package/callbacks/promises.js +0 -1
- package/chat_history.cjs +0 -1
- package/chat_history.d.cts +0 -1
- package/chat_history.d.ts +0 -1
- package/chat_history.js +0 -1
- package/context.cjs +0 -1
- package/context.d.cts +0 -1
- package/context.d.ts +0 -1
- package/context.js +0 -1
- package/document_loaders/base.cjs +0 -1
- package/document_loaders/base.d.cts +0 -1
- package/document_loaders/base.d.ts +0 -1
- package/document_loaders/base.js +0 -1
- package/document_loaders/langsmith.cjs +0 -1
- package/document_loaders/langsmith.d.cts +0 -1
- package/document_loaders/langsmith.d.ts +0 -1
- package/document_loaders/langsmith.js +0 -1
- package/documents.cjs +0 -1
- package/documents.d.cts +0 -1
- package/documents.d.ts +0 -1
- package/documents.js +0 -1
- package/embeddings.cjs +0 -1
- package/embeddings.d.cts +0 -1
- package/embeddings.d.ts +0 -1
- package/embeddings.js +0 -1
- package/example_selectors.cjs +0 -1
- package/example_selectors.d.cts +0 -1
- package/example_selectors.d.ts +0 -1
- package/example_selectors.js +0 -1
- package/indexing.cjs +0 -1
- package/indexing.d.cts +0 -1
- package/indexing.d.ts +0 -1
- package/indexing.js +0 -1
- package/language_models/base.cjs +0 -1
- package/language_models/base.d.cts +0 -1
- package/language_models/base.d.ts +0 -1
- package/language_models/base.js +0 -1
- package/language_models/chat_models.cjs +0 -1
- package/language_models/chat_models.d.cts +0 -1
- package/language_models/chat_models.d.ts +0 -1
- package/language_models/chat_models.js +0 -1
- package/language_models/llms.cjs +0 -1
- package/language_models/llms.d.cts +0 -1
- package/language_models/llms.d.ts +0 -1
- package/language_models/llms.js +0 -1
- package/language_models/profile.cjs +0 -1
- package/language_models/profile.d.cts +0 -1
- package/language_models/profile.d.ts +0 -1
- package/language_models/profile.js +0 -1
- package/load/serializable.cjs +0 -1
- package/load/serializable.d.cts +0 -1
- package/load/serializable.d.ts +0 -1
- package/load/serializable.js +0 -1
- package/load.cjs +0 -1
- package/load.d.cts +0 -1
- package/load.d.ts +0 -1
- package/load.js +0 -1
- package/memory.cjs +0 -1
- package/memory.d.cts +0 -1
- package/memory.d.ts +0 -1
- package/memory.js +0 -1
- package/messages/tool.cjs +0 -1
- package/messages/tool.d.cts +0 -1
- package/messages/tool.d.ts +0 -1
- package/messages/tool.js +0 -1
- package/messages.cjs +0 -1
- package/messages.d.cts +0 -1
- package/messages.d.ts +0 -1
- package/messages.js +0 -1
- package/output_parsers/openai_functions.cjs +0 -1
- package/output_parsers/openai_functions.d.cts +0 -1
- package/output_parsers/openai_functions.d.ts +0 -1
- package/output_parsers/openai_functions.js +0 -1
- package/output_parsers/openai_tools.cjs +0 -1
- package/output_parsers/openai_tools.d.cts +0 -1
- package/output_parsers/openai_tools.d.ts +0 -1
- package/output_parsers/openai_tools.js +0 -1
- package/output_parsers.cjs +0 -1
- package/output_parsers.d.cts +0 -1
- package/output_parsers.d.ts +0 -1
- package/output_parsers.js +0 -1
- package/outputs.cjs +0 -1
- package/outputs.d.cts +0 -1
- package/outputs.d.ts +0 -1
- package/outputs.js +0 -1
- package/prompt_values.cjs +0 -1
- package/prompt_values.d.cts +0 -1
- package/prompt_values.d.ts +0 -1
- package/prompt_values.js +0 -1
- package/prompts.cjs +0 -1
- package/prompts.d.cts +0 -1
- package/prompts.d.ts +0 -1
- package/prompts.js +0 -1
- package/retrievers/document_compressors.cjs +0 -1
- package/retrievers/document_compressors.d.cts +0 -1
- package/retrievers/document_compressors.d.ts +0 -1
- package/retrievers/document_compressors.js +0 -1
- package/retrievers.cjs +0 -1
- package/retrievers.d.cts +0 -1
- package/retrievers.d.ts +0 -1
- package/retrievers.js +0 -1
- package/runnables/graph.cjs +0 -1
- package/runnables/graph.d.cts +0 -1
- package/runnables/graph.d.ts +0 -1
- package/runnables/graph.js +0 -1
- package/runnables.cjs +0 -1
- package/runnables.d.cts +0 -1
- package/runnables.d.ts +0 -1
- package/runnables.js +0 -1
- package/singletons.cjs +0 -1
- package/singletons.d.cts +0 -1
- package/singletons.d.ts +0 -1
- package/singletons.js +0 -1
- package/stores.cjs +0 -1
- package/stores.d.cts +0 -1
- package/stores.d.ts +0 -1
- package/stores.js +0 -1
- package/structured_query.cjs +0 -1
- package/structured_query.d.cts +0 -1
- package/structured_query.d.ts +0 -1
- package/structured_query.js +0 -1
- package/tools.cjs +0 -1
- package/tools.d.cts +0 -1
- package/tools.d.ts +0 -1
- package/tools.js +0 -1
- package/tracers/base.cjs +0 -1
- package/tracers/base.d.cts +0 -1
- package/tracers/base.d.ts +0 -1
- package/tracers/base.js +0 -1
- package/tracers/console.cjs +0 -1
- package/tracers/console.d.cts +0 -1
- package/tracers/console.d.ts +0 -1
- package/tracers/console.js +0 -1
- package/tracers/log_stream.cjs +0 -1
- package/tracers/log_stream.d.cts +0 -1
- package/tracers/log_stream.d.ts +0 -1
- package/tracers/log_stream.js +0 -1
- package/tracers/run_collector.cjs +0 -1
- package/tracers/run_collector.d.cts +0 -1
- package/tracers/run_collector.d.ts +0 -1
- package/tracers/run_collector.js +0 -1
- package/tracers/tracer_langchain.cjs +0 -1
- package/tracers/tracer_langchain.d.cts +0 -1
- package/tracers/tracer_langchain.d.ts +0 -1
- package/tracers/tracer_langchain.js +0 -1
- package/types/stream.cjs +0 -1
- package/types/stream.d.cts +0 -1
- package/types/stream.d.ts +0 -1
- package/types/stream.js +0 -1
- package/utils/async_caller.cjs +0 -1
- package/utils/async_caller.d.cts +0 -1
- package/utils/async_caller.d.ts +0 -1
- package/utils/async_caller.js +0 -1
- package/utils/chunk_array.cjs +0 -1
- package/utils/chunk_array.d.cts +0 -1
- package/utils/chunk_array.d.ts +0 -1
- package/utils/chunk_array.js +0 -1
- package/utils/context.cjs +0 -1
- package/utils/context.d.cts +0 -1
- package/utils/context.d.ts +0 -1
- package/utils/context.js +0 -1
- package/utils/env.cjs +0 -1
- package/utils/env.d.cts +0 -1
- package/utils/env.d.ts +0 -1
- package/utils/env.js +0 -1
- package/utils/event_source_parse.cjs +0 -1
- package/utils/event_source_parse.d.cts +0 -1
- package/utils/event_source_parse.d.ts +0 -1
- package/utils/event_source_parse.js +0 -1
- package/utils/format.cjs +0 -1
- package/utils/format.d.cts +0 -1
- package/utils/format.d.ts +0 -1
- package/utils/format.js +0 -1
- package/utils/function_calling.cjs +0 -1
- package/utils/function_calling.d.cts +0 -1
- package/utils/function_calling.d.ts +0 -1
- package/utils/function_calling.js +0 -1
- package/utils/hash.cjs +0 -1
- package/utils/hash.d.cts +0 -1
- package/utils/hash.d.ts +0 -1
- package/utils/hash.js +0 -1
- package/utils/json_patch.cjs +0 -1
- package/utils/json_patch.d.cts +0 -1
- package/utils/json_patch.d.ts +0 -1
- package/utils/json_patch.js +0 -1
- package/utils/json_schema.cjs +0 -1
- package/utils/json_schema.d.cts +0 -1
- package/utils/json_schema.d.ts +0 -1
- package/utils/json_schema.js +0 -1
- package/utils/math.cjs +0 -1
- package/utils/math.d.cts +0 -1
- package/utils/math.d.ts +0 -1
- package/utils/math.js +0 -1
- package/utils/stream.cjs +0 -1
- package/utils/stream.d.cts +0 -1
- package/utils/stream.d.ts +0 -1
- package/utils/stream.js +0 -1
- package/utils/testing.cjs +0 -1
- package/utils/testing.d.cts +0 -1
- package/utils/testing.d.ts +0 -1
- package/utils/testing.js +0 -1
- package/utils/tiktoken.cjs +0 -1
- package/utils/tiktoken.d.cts +0 -1
- package/utils/tiktoken.d.ts +0 -1
- package/utils/tiktoken.js +0 -1
- package/utils/types.cjs +0 -1
- package/utils/types.d.cts +0 -1
- package/utils/types.d.ts +0 -1
- package/utils/types.js +0 -1
- package/vectorstores.cjs +0 -1
- package/vectorstores.d.cts +0 -1
- package/vectorstores.d.ts +0 -1
- package/vectorstores.js +0 -1
package/dist/prompts/dict.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dict.js","names":["fields: {\n template: Record<string, unknown>;\n templateFormat?: TemplateFormat;\n }","values: TypedPromptInputValues<RunInput>","values: TypedPromptInputValues<InputValues>","template: Record<string, unknown>","templateFormat: TemplateFormat","inputVariables: Array<Extract<keyof InputValues, string>>","inputs: TypedPromptInputValues<InputValues>","formatted: Record<string, unknown>","formattedV: Array<unknown>"],"sources":["../../src/prompts/dict.ts"],"sourcesContent":["import { Runnable } from \"../runnables/base.js\";\nimport type { InputValues } from \"../utils/types/index.js\";\nimport { TypedPromptInputValues } from \"./base.js\";\nimport { parseTemplate, renderTemplate, TemplateFormat } from \"./template.js\";\n\nexport class DictPromptTemplate<\n RunInput extends InputValues = InputValues,\n RunOutput extends Record<string, unknown> = Record<string, unknown
|
|
1
|
+
{"version":3,"file":"dict.js","names":["fields: {\n template: Record<string, unknown>;\n templateFormat?: TemplateFormat;\n }","values: TypedPromptInputValues<RunInput>","values: TypedPromptInputValues<InputValues>","template: Record<string, unknown>","templateFormat: TemplateFormat","inputVariables: Array<Extract<keyof InputValues, string>>","inputs: TypedPromptInputValues<InputValues>","formatted: Record<string, unknown>","formattedV: Array<unknown>"],"sources":["../../src/prompts/dict.ts"],"sourcesContent":["import { Runnable } from \"../runnables/base.js\";\nimport type { InputValues } from \"../utils/types/index.js\";\nimport { TypedPromptInputValues } from \"./base.js\";\nimport { parseTemplate, renderTemplate, TemplateFormat } from \"./template.js\";\n\nexport class DictPromptTemplate<\n RunInput extends InputValues = InputValues,\n RunOutput extends Record<string, unknown> = Record<string, unknown>,\n> extends Runnable<TypedPromptInputValues<RunInput>, RunOutput> {\n lc_namespace = [\"langchain_core\", \"prompts\", \"dict\"];\n\n lc_serializable = true;\n\n template: Record<string, unknown>;\n\n templateFormat: TemplateFormat;\n\n inputVariables: Array<Extract<keyof RunInput, string>>;\n\n static lc_name() {\n return \"DictPromptTemplate\";\n }\n\n constructor(fields: {\n template: Record<string, unknown>;\n templateFormat?: TemplateFormat;\n }) {\n const templateFormat = fields.templateFormat ?? \"f-string\";\n const inputVariables = _getInputVariables(\n fields.template,\n templateFormat\n ) as Array<Extract<keyof RunInput, string>>;\n super({ inputVariables, ...fields });\n this.template = fields.template;\n this.templateFormat = templateFormat;\n this.inputVariables = inputVariables;\n }\n\n async format(values: TypedPromptInputValues<RunInput>): Promise<RunOutput> {\n return _insertInputVariables(\n this.template,\n values,\n this.templateFormat\n ) as RunOutput;\n }\n\n async invoke(\n values: TypedPromptInputValues<InputValues>\n ): Promise<RunOutput> {\n return await this._callWithConfig(this.format.bind(this), values, {\n runType: \"prompt\",\n });\n }\n}\n\nfunction _getInputVariables(\n template: Record<string, unknown>,\n templateFormat: TemplateFormat\n): Array<Extract<keyof InputValues, string>> {\n const inputVariables: Array<Extract<keyof InputValues, string>> = [];\n for (const v of Object.values(template)) {\n if (typeof v === \"string\") {\n parseTemplate(v, templateFormat).forEach((t) => {\n if (t.type === \"variable\") {\n inputVariables.push(t.name);\n }\n });\n } else if (Array.isArray(v)) {\n for (const x of v) {\n if (typeof x === \"string\") {\n parseTemplate(x, templateFormat).forEach((t) => {\n if (t.type === \"variable\") {\n inputVariables.push(t.name);\n }\n });\n } else if (typeof x === \"object\") {\n inputVariables.push(..._getInputVariables(x, templateFormat));\n }\n }\n } else if (typeof v === \"object\" && v !== null) {\n inputVariables.push(\n ..._getInputVariables(v as Record<string, unknown>, templateFormat)\n );\n }\n }\n return Array.from(new Set(inputVariables));\n}\n\nfunction _insertInputVariables(\n template: Record<string, unknown>,\n inputs: TypedPromptInputValues<InputValues>,\n templateFormat: TemplateFormat\n): Record<string, unknown> {\n const formatted: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(template)) {\n if (typeof v === \"string\") {\n formatted[k] = renderTemplate(v, templateFormat, inputs);\n } else if (Array.isArray(v)) {\n const formattedV: Array<unknown> = [];\n for (const x of v) {\n if (typeof x === \"string\") {\n formattedV.push(renderTemplate(x, templateFormat, inputs));\n } else if (typeof x === \"object\") {\n formattedV.push(_insertInputVariables(x, inputs, templateFormat));\n }\n }\n formatted[k] = formattedV;\n } else if (typeof v === \"object\" && v !== null) {\n formatted[k] = _insertInputVariables(\n v as Record<string, unknown>,\n inputs,\n templateFormat\n );\n } else {\n formatted[k] = v;\n }\n }\n return formatted;\n}\n"],"mappings":";;;;AAKA,IAAa,qBAAb,cAGU,SAAsD;CAC9D,eAAe;EAAC;EAAkB;EAAW;CAAO;CAEpD,kBAAkB;CAElB;CAEA;CAEA;CAEA,OAAO,UAAU;AACf,SAAO;CACR;CAED,YAAYA,QAGT;EACD,MAAM,iBAAiB,OAAO,kBAAkB;EAChD,MAAM,iBAAiB,mBACrB,OAAO,UACP,eACD;EACD,MAAM;GAAE;GAAgB,GAAG;EAAQ,EAAC;EACpC,KAAK,WAAW,OAAO;EACvB,KAAK,iBAAiB;EACtB,KAAK,iBAAiB;CACvB;CAED,MAAM,OAAOC,QAA8D;AAC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GrE,UAAU,KAAK;CAChB,WAAU,OAAO,MAAM,YAAY,MAAM,MACxC,UAAU,KAAK,sBACb,GACA,QACA,eACD;MAED,UAAU,KAAK;AAGnB,QAAO;AACR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"few_shot.cjs","names":["BaseStringPromptTemplate","input: FewShotPromptTemplateInput","totalInputVariables: string[]","checkValidTemplate","inputVariables: InputValues","values: PartialValues<NewPartialVariableName>","values: InputValues","renderTemplate","data: SerializedFewShotTemplate","PromptTemplate","examples: Example[]","BaseChatPromptTemplate","fields: FewShotChatMessagePromptTemplateInput","values: TypedPromptInputValues<RunInput>","result: Record<string, any>","messages: BaseMessage[]","values: PartialValues<PartialVariableName>"],"sources":["../../src/prompts/few_shot.ts"],"sourcesContent":["import { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n Example,\n} from \"./base.js\";\nimport type { BaseExampleSelector } from \"../example_selectors/base.js\";\nimport {\n type TemplateFormat,\n checkValidTemplate,\n renderTemplate,\n} from \"./template.js\";\nimport { PromptTemplate } from \"./prompt.js\";\nimport type { SerializedFewShotTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport type { BaseMessage } from \"../messages/index.js\";\nimport {\n BaseChatPromptTemplate,\n type BaseMessagePromptTemplate,\n} from \"./chat.js\";\n\nexport interface FewShotPromptTemplateInput\n extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector;\n\n /**\n * An {@link PromptTemplate} used to format a single example.\n */\n examplePrompt: PromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n */\n exampleSeparator?: string;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Prompt template that contains few-shot examples.\n * @augments BasePromptTemplate\n * @augments FewShotPromptTemplateInput\n * @example\n * ```typescript\n * const examplePrompt = PromptTemplate.fromTemplate(\n * \"Input: {input}\\nOutput: {output}\",\n * );\n *\n * const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples(\n * [\n * { input: \"happy\", output: \"sad\" },\n * { input: \"tall\", output: \"short\" },\n * { input: \"energetic\", output: \"lethargic\" },\n * { input: \"sunny\", output: \"gloomy\" },\n * { input: \"windy\", output: \"calm\" },\n * ],\n * new OpenAIEmbeddings(),\n * HNSWLib,\n * { k: 1 },\n * );\n *\n * const dynamicPrompt = new FewShotPromptTemplate({\n * exampleSelector,\n * examplePrompt,\n * prefix: \"Give the antonym of every input\",\n * suffix: \"Input: {adjective}\\nOutput:\",\n * inputVariables: [\"adjective\"],\n * });\n *\n * // Format the dynamic prompt with the input 'rainy'\n * console.log(await dynamicPrompt.format({ adjective: \"rainy\" }));\n *\n * ```\n */\nexport class FewShotPromptTemplate\n extends BaseStringPromptTemplate\n implements FewShotPromptTemplateInput\n{\n lc_serializable = false;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: PromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n constructor(input: FewShotPromptTemplateInput) {\n super(input);\n Object.assign(this, input);\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"few_shot\" {\n return \"few_shot\";\n }\n\n static lc_name() {\n return \"FewShotPromptTemplate\";\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n );\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n };\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotPromptTemplate(promptDict);\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: InputValues): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n\n const exampleStrings = await Promise.all(\n examples.map((example) => this.examplePrompt.format(example))\n );\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n serialize(): SerializedFewShotTemplate {\n if (this.exampleSelector || !this.examples) {\n throw new Error(\n \"Serializing an example selector is not currently supported\"\n );\n }\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Serializing an output parser is not currently supported\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n example_prompt: this.examplePrompt.serialize(),\n example_separator: this.exampleSeparator,\n suffix: this.suffix,\n prefix: this.prefix,\n template_format: this.templateFormat,\n examples: this.examples,\n };\n }\n\n static async deserialize(\n data: SerializedFewShotTemplate\n ): Promise<FewShotPromptTemplate> {\n const { example_prompt } = data;\n if (!example_prompt) {\n throw new Error(\"Missing example prompt\");\n }\n const examplePrompt = await PromptTemplate.deserialize(example_prompt);\n\n let examples: Example[];\n\n if (Array.isArray(data.examples)) {\n examples = data.examples;\n } else {\n throw new Error(\n \"Invalid examples format. Only list or string are supported.\"\n );\n }\n\n return new FewShotPromptTemplate({\n inputVariables: data.input_variables,\n examplePrompt,\n examples,\n exampleSeparator: data.example_separator,\n prefix: data.prefix,\n suffix: data.suffix,\n templateFormat: data.template_format,\n });\n }\n}\n\nexport interface FewShotChatMessagePromptTemplateInput\n extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseMessagePromptTemplate} | {@link BaseChatPromptTemplate} used to format a single example.\n */\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n *\n * @defaultValue `\"\\n\\n\"`\n */\n exampleSeparator?: string;\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector | undefined;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n *\n * @defaultValue `\"\"`\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n *\n * @defaultValue `f-string`\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Chat prompt template that contains few-shot examples.\n * @augments BasePromptTemplateInput\n * @augments FewShotChatMessagePromptTemplateInput\n */\nexport class FewShotChatMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any\n >\n extends BaseChatPromptTemplate\n implements FewShotChatMessagePromptTemplateInput\n{\n lc_serializable = true;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n _getPromptType(): \"few_shot_chat\" {\n return \"few_shot_chat\";\n }\n\n static lc_name() {\n return \"FewShotChatMessagePromptTemplate\";\n }\n\n constructor(fields: FewShotChatMessagePromptTemplateInput) {\n super(fields);\n\n this.examples = fields.examples;\n this.examplePrompt = fields.examplePrompt;\n this.exampleSeparator = fields.exampleSeparator ?? \"\\n\\n\";\n this.exampleSelector = fields.exampleSelector;\n this.prefix = fields.prefix ?? \"\";\n this.suffix = fields.suffix ?? \"\";\n this.templateFormat = fields.templateFormat ?? \"f-string\";\n this.validateTemplate = fields.validateTemplate ?? true;\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n /**\n * Formats the list of values and returns a list of formatted messages.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n const allValues = await this.mergePartialAndUserVariables(values);\n let examples = await this.getExamples(allValues);\n\n examples = examples.map((example) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n this.examplePrompt.inputVariables.forEach((inputVariable) => {\n result[inputVariable] = example[inputVariable];\n });\n return result;\n });\n\n const messages: BaseMessage[] = [];\n for (const example of examples) {\n const exampleMessages = await this.examplePrompt.formatMessages(example);\n messages.push(...exampleMessages);\n }\n return messages;\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n const exampleMessages = await Promise.all(\n examples.map((example) => this.examplePrompt.formatMessages(example))\n );\n const exampleStrings = exampleMessages\n .flat()\n .map((message) => message.content);\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n /**\n * Partially formats the prompt with the given values.\n * @param values The values to partially format the prompt with.\n * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted.\n */\n async partial(\n values: PartialValues<PartialVariableName>\n ): Promise<FewShotChatMessagePromptTemplate<RunInput, PartialVariableName>> {\n const newInputVariables = this.inputVariables.filter(\n (variable) => !(variable in values)\n ) as Exclude<Extract<keyof RunInput, string>, PartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | PartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotChatMessagePromptTemplate<\n InputValues<Exclude<Extract<keyof RunInput, string>, PartialVariableName>>\n >(promptDict);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,IAAa,wBAAb,MAAa,8BACHA,wCAEV;CACE,kBAAkB;CAElB;CAEA;CAEA;CAEA,SAAS;CAET,mBAAmB;CAEnB,SAAS;CAET,iBAAiC;CAEjC,mBAAmB;CAEnB,YAAYC,OAAmC;EAC7C,MAAM,MAAM;EACZ,OAAO,OAAO,MAAM,MAAM;AAE1B,MAAI,KAAK,aAAa,UAAa,KAAK,oBAAoB,OAC1D,OAAM,IAAI,MACR;AAIJ,MAAI,KAAK,aAAa,UAAa,KAAK,oBAAoB,OAC1D,OAAM,IAAI,MACR;AAIJ,MAAI,KAAK,kBAAkB;GACzB,IAAIC,sBAAgC,KAAK;AACzC,OAAI,KAAK,kBACP,sBAAsB,oBAAoB,OACxC,OAAO,KAAK,KAAK,iBAAiB,CACnC;GAEHC,oCACE,KAAK,SAAS,KAAK,QACnB,KAAK,gBACL,oBACD;EACF;CACF;CAED,iBAA6B;AAC3B,SAAO;CACR;CAED,OAAO,UAAU;AACf,SAAO;CACR;CAED,MAAc,YACZC,gBACwB;AACxB,MAAI,KAAK,aAAa,OACpB,QAAO,KAAK;AAEd,MAAI,KAAK,oBAAoB,OAC3B,QAAO,KAAK,gBAAgB,eAAe,eAAe;AAG5D,QAAM,IAAI,MACR;CAEH;CAED,MAAM,QACJC,QACA;EACA,MAAM,oBAAoB,KAAK,eAAe,OAC5C,CAAC,OAAO,EAAE,MAAM,QACjB;EACD,MAAM,sBAAsB;GAC1B,GAAI,KAAK,oBAAoB,CAAE;GAC/B,GAAG;EACJ;EACD,MAAM,aAAa;GACjB,GAAG;GACH,gBAAgB;GAChB,kBAAkB;EACnB;AACD,SAAO,IAAI,sBAAsB;CAClC;;;;;;CAOD,MAAM,OAAO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AK,GAAG,gBAAgB;EAClC;AACD,SAAO;CACR;;;;;;CAOD,MAAM,OAAOF,QAA2D;EACtE,MAAM,YAAY,MAAM,KAAK,6BAA6B,OAAO;EACjE,MAAM,WAAW,MAAM,KAAK,YAAY,UAAU;EAClD,MAAM,kBAAkB,MAAM,QAAQ,IACpC,SAAS,IAAI,CAAC,YAAY,KAAK,cAAc,eAAe,QAAQ,CAAC,CACtE;EACD,MAAM,iBAAiB,gBACpB,MAAM,CACN,IAAI,CAAC,YAAY,QAAQ,QAAQ;EACpC,MAAM,WAAW;GAAC,KAAK;GAAQ,GAAG;GAAgB,KAAK;EAAO,EAAC,KAC7D,KAAK,iBACN;AACD,SAAON,gCAAe,UAAU,KAAK,gBAAgB,UAAU;CAChE;;;;;;CAOD,MAAM,QACJS,QAC0E;EAC1E,MAAM,oBAAoB,KAAK,eAAe,OAC5C,CAAC,aAAa,EAAE,YAAY,QAC7B;EACD,MAAM,sBAAsB;GAC1B,GAAI,KAAK,oBAAoB,CAAE;GAC/B,GAAG;EACJ;EACD,MAAM,aAAa;GACjB,GAAG;GACH,gBAAgB;GAChB,kBAAkB;EACnB;AACD,SAAO,IAAI,iCAET;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"few_shot.cjs","names":["BaseStringPromptTemplate","input: FewShotPromptTemplateInput","totalInputVariables: string[]","checkValidTemplate","inputVariables: InputValues","values: PartialValues<NewPartialVariableName>","values: InputValues","renderTemplate","data: SerializedFewShotTemplate","PromptTemplate","examples: Example[]","BaseChatPromptTemplate","fields: FewShotChatMessagePromptTemplateInput","values: TypedPromptInputValues<RunInput>","result: Record<string, any>","messages: BaseMessage[]","values: PartialValues<PartialVariableName>"],"sources":["../../src/prompts/few_shot.ts"],"sourcesContent":["import { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n Example,\n} from \"./base.js\";\nimport type { BaseExampleSelector } from \"../example_selectors/base.js\";\nimport {\n type TemplateFormat,\n checkValidTemplate,\n renderTemplate,\n} from \"./template.js\";\nimport { PromptTemplate } from \"./prompt.js\";\nimport type { SerializedFewShotTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport type { BaseMessage } from \"../messages/index.js\";\nimport {\n BaseChatPromptTemplate,\n type BaseMessagePromptTemplate,\n} from \"./chat.js\";\n\nexport interface FewShotPromptTemplateInput\n extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector;\n\n /**\n * An {@link PromptTemplate} used to format a single example.\n */\n examplePrompt: PromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n */\n exampleSeparator?: string;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Prompt template that contains few-shot examples.\n * @augments BasePromptTemplate\n * @augments FewShotPromptTemplateInput\n * @example\n * ```typescript\n * const examplePrompt = PromptTemplate.fromTemplate(\n * \"Input: {input}\\nOutput: {output}\",\n * );\n *\n * const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples(\n * [\n * { input: \"happy\", output: \"sad\" },\n * { input: \"tall\", output: \"short\" },\n * { input: \"energetic\", output: \"lethargic\" },\n * { input: \"sunny\", output: \"gloomy\" },\n * { input: \"windy\", output: \"calm\" },\n * ],\n * new OpenAIEmbeddings(),\n * HNSWLib,\n * { k: 1 },\n * );\n *\n * const dynamicPrompt = new FewShotPromptTemplate({\n * exampleSelector,\n * examplePrompt,\n * prefix: \"Give the antonym of every input\",\n * suffix: \"Input: {adjective}\\nOutput:\",\n * inputVariables: [\"adjective\"],\n * });\n *\n * // Format the dynamic prompt with the input 'rainy'\n * console.log(await dynamicPrompt.format({ adjective: \"rainy\" }));\n *\n * ```\n */\nexport class FewShotPromptTemplate\n extends BaseStringPromptTemplate\n implements FewShotPromptTemplateInput\n{\n lc_serializable = false;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: PromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n constructor(input: FewShotPromptTemplateInput) {\n super(input);\n Object.assign(this, input);\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"few_shot\" {\n return \"few_shot\";\n }\n\n static lc_name() {\n return \"FewShotPromptTemplate\";\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n );\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n };\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotPromptTemplate(promptDict);\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: InputValues): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n\n const exampleStrings = await Promise.all(\n examples.map((example) => this.examplePrompt.format(example))\n );\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n serialize(): SerializedFewShotTemplate {\n if (this.exampleSelector || !this.examples) {\n throw new Error(\n \"Serializing an example selector is not currently supported\"\n );\n }\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Serializing an output parser is not currently supported\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n example_prompt: this.examplePrompt.serialize(),\n example_separator: this.exampleSeparator,\n suffix: this.suffix,\n prefix: this.prefix,\n template_format: this.templateFormat,\n examples: this.examples,\n };\n }\n\n static async deserialize(\n data: SerializedFewShotTemplate\n ): Promise<FewShotPromptTemplate> {\n const { example_prompt } = data;\n if (!example_prompt) {\n throw new Error(\"Missing example prompt\");\n }\n const examplePrompt = await PromptTemplate.deserialize(example_prompt);\n\n let examples: Example[];\n\n if (Array.isArray(data.examples)) {\n examples = data.examples;\n } else {\n throw new Error(\n \"Invalid examples format. Only list or string are supported.\"\n );\n }\n\n return new FewShotPromptTemplate({\n inputVariables: data.input_variables,\n examplePrompt,\n examples,\n exampleSeparator: data.example_separator,\n prefix: data.prefix,\n suffix: data.suffix,\n templateFormat: data.template_format,\n });\n }\n}\n\nexport interface FewShotChatMessagePromptTemplateInput\n extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseMessagePromptTemplate} | {@link BaseChatPromptTemplate} used to format a single example.\n */\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n *\n * @defaultValue `\"\\n\\n\"`\n */\n exampleSeparator?: string;\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector | undefined;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n *\n * @defaultValue `\"\"`\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n *\n * @defaultValue `f-string`\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Chat prompt template that contains few-shot examples.\n * @augments BasePromptTemplateInput\n * @augments FewShotChatMessagePromptTemplateInput\n */\nexport class FewShotChatMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n >\n extends BaseChatPromptTemplate\n implements FewShotChatMessagePromptTemplateInput\n{\n lc_serializable = true;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n _getPromptType(): \"few_shot_chat\" {\n return \"few_shot_chat\";\n }\n\n static lc_name() {\n return \"FewShotChatMessagePromptTemplate\";\n }\n\n constructor(fields: FewShotChatMessagePromptTemplateInput) {\n super(fields);\n\n this.examples = fields.examples;\n this.examplePrompt = fields.examplePrompt;\n this.exampleSeparator = fields.exampleSeparator ?? \"\\n\\n\";\n this.exampleSelector = fields.exampleSelector;\n this.prefix = fields.prefix ?? \"\";\n this.suffix = fields.suffix ?? \"\";\n this.templateFormat = fields.templateFormat ?? \"f-string\";\n this.validateTemplate = fields.validateTemplate ?? true;\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n /**\n * Formats the list of values and returns a list of formatted messages.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n const allValues = await this.mergePartialAndUserVariables(values);\n let examples = await this.getExamples(allValues);\n\n examples = examples.map((example) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n this.examplePrompt.inputVariables.forEach((inputVariable) => {\n result[inputVariable] = example[inputVariable];\n });\n return result;\n });\n\n const messages: BaseMessage[] = [];\n for (const example of examples) {\n const exampleMessages = await this.examplePrompt.formatMessages(example);\n messages.push(...exampleMessages);\n }\n return messages;\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n const exampleMessages = await Promise.all(\n examples.map((example) => this.examplePrompt.formatMessages(example))\n );\n const exampleStrings = exampleMessages\n .flat()\n .map((message) => message.content);\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n /**\n * Partially formats the prompt with the given values.\n * @param values The values to partially format the prompt with.\n * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted.\n */\n async partial(\n values: PartialValues<PartialVariableName>\n ): Promise<FewShotChatMessagePromptTemplate<RunInput, PartialVariableName>> {\n const newInputVariables = this.inputVariables.filter(\n (variable) => !(variable in values)\n ) as Exclude<Extract<keyof RunInput, string>, PartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | PartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotChatMessagePromptTemplate<\n InputValues<Exclude<Extract<keyof RunInput, string>, PartialVariableName>>\n >(promptDict);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,IAAa,wBAAb,MAAa,8BACHA,wCAEV;CACE,kBAAkB;CAElB;CAEA;CAEA;CAEA,SAAS;CAET,mBAAmB;CAEnB,SAAS;CAET,iBAAiC;CAEjC,mBAAmB;CAEnB,YAAYC,OAAmC;EAC7C,MAAM,MAAM;EACZ,OAAO,OAAO,MAAM,MAAM;AAE1B,MAAI,KAAK,aAAa,UAAa,KAAK,oBAAoB,OAC1D,OAAM,IAAI,MACR;AAIJ,MAAI,KAAK,aAAa,UAAa,KAAK,oBAAoB,OAC1D,OAAM,IAAI,MACR;AAIJ,MAAI,KAAK,kBAAkB;GACzB,IAAIC,sBAAgC,KAAK;AACzC,OAAI,KAAK,kBACP,sBAAsB,oBAAoB,OACxC,OAAO,KAAK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J;EACD,MAAM,aAAa;GACjB,GAAG;GACH,gBAAgB;GAChB,kBAAkB;EACnB;AACD,SAAO,IAAI,iCAET;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"few_shot.js","names":["input: FewShotPromptTemplateInput","totalInputVariables: string[]","inputVariables: InputValues","values: PartialValues<NewPartialVariableName>","values: InputValues","data: SerializedFewShotTemplate","examples: Example[]","fields: FewShotChatMessagePromptTemplateInput","values: TypedPromptInputValues<RunInput>","result: Record<string, any>","messages: BaseMessage[]","values: PartialValues<PartialVariableName>"],"sources":["../../src/prompts/few_shot.ts"],"sourcesContent":["import { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n Example,\n} from \"./base.js\";\nimport type { BaseExampleSelector } from \"../example_selectors/base.js\";\nimport {\n type TemplateFormat,\n checkValidTemplate,\n renderTemplate,\n} from \"./template.js\";\nimport { PromptTemplate } from \"./prompt.js\";\nimport type { SerializedFewShotTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport type { BaseMessage } from \"../messages/index.js\";\nimport {\n BaseChatPromptTemplate,\n type BaseMessagePromptTemplate,\n} from \"./chat.js\";\n\nexport interface FewShotPromptTemplateInput\n extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector;\n\n /**\n * An {@link PromptTemplate} used to format a single example.\n */\n examplePrompt: PromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n */\n exampleSeparator?: string;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Prompt template that contains few-shot examples.\n * @augments BasePromptTemplate\n * @augments FewShotPromptTemplateInput\n * @example\n * ```typescript\n * const examplePrompt = PromptTemplate.fromTemplate(\n * \"Input: {input}\\nOutput: {output}\",\n * );\n *\n * const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples(\n * [\n * { input: \"happy\", output: \"sad\" },\n * { input: \"tall\", output: \"short\" },\n * { input: \"energetic\", output: \"lethargic\" },\n * { input: \"sunny\", output: \"gloomy\" },\n * { input: \"windy\", output: \"calm\" },\n * ],\n * new OpenAIEmbeddings(),\n * HNSWLib,\n * { k: 1 },\n * );\n *\n * const dynamicPrompt = new FewShotPromptTemplate({\n * exampleSelector,\n * examplePrompt,\n * prefix: \"Give the antonym of every input\",\n * suffix: \"Input: {adjective}\\nOutput:\",\n * inputVariables: [\"adjective\"],\n * });\n *\n * // Format the dynamic prompt with the input 'rainy'\n * console.log(await dynamicPrompt.format({ adjective: \"rainy\" }));\n *\n * ```\n */\nexport class FewShotPromptTemplate\n extends BaseStringPromptTemplate\n implements FewShotPromptTemplateInput\n{\n lc_serializable = false;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: PromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n constructor(input: FewShotPromptTemplateInput) {\n super(input);\n Object.assign(this, input);\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"few_shot\" {\n return \"few_shot\";\n }\n\n static lc_name() {\n return \"FewShotPromptTemplate\";\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n );\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n };\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotPromptTemplate(promptDict);\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: InputValues): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n\n const exampleStrings = await Promise.all(\n examples.map((example) => this.examplePrompt.format(example))\n );\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n serialize(): SerializedFewShotTemplate {\n if (this.exampleSelector || !this.examples) {\n throw new Error(\n \"Serializing an example selector is not currently supported\"\n );\n }\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Serializing an output parser is not currently supported\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n example_prompt: this.examplePrompt.serialize(),\n example_separator: this.exampleSeparator,\n suffix: this.suffix,\n prefix: this.prefix,\n template_format: this.templateFormat,\n examples: this.examples,\n };\n }\n\n static async deserialize(\n data: SerializedFewShotTemplate\n ): Promise<FewShotPromptTemplate> {\n const { example_prompt } = data;\n if (!example_prompt) {\n throw new Error(\"Missing example prompt\");\n }\n const examplePrompt = await PromptTemplate.deserialize(example_prompt);\n\n let examples: Example[];\n\n if (Array.isArray(data.examples)) {\n examples = data.examples;\n } else {\n throw new Error(\n \"Invalid examples format. Only list or string are supported.\"\n );\n }\n\n return new FewShotPromptTemplate({\n inputVariables: data.input_variables,\n examplePrompt,\n examples,\n exampleSeparator: data.example_separator,\n prefix: data.prefix,\n suffix: data.suffix,\n templateFormat: data.template_format,\n });\n }\n}\n\nexport interface FewShotChatMessagePromptTemplateInput\n extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseMessagePromptTemplate} | {@link BaseChatPromptTemplate} used to format a single example.\n */\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n *\n * @defaultValue `\"\\n\\n\"`\n */\n exampleSeparator?: string;\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector | undefined;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n *\n * @defaultValue `\"\"`\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n *\n * @defaultValue `f-string`\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Chat prompt template that contains few-shot examples.\n * @augments BasePromptTemplateInput\n * @augments FewShotChatMessagePromptTemplateInput\n */\nexport class FewShotChatMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any\n >\n extends BaseChatPromptTemplate\n implements FewShotChatMessagePromptTemplateInput\n{\n lc_serializable = true;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n _getPromptType(): \"few_shot_chat\" {\n return \"few_shot_chat\";\n }\n\n static lc_name() {\n return \"FewShotChatMessagePromptTemplate\";\n }\n\n constructor(fields: FewShotChatMessagePromptTemplateInput) {\n super(fields);\n\n this.examples = fields.examples;\n this.examplePrompt = fields.examplePrompt;\n this.exampleSeparator = fields.exampleSeparator ?? \"\\n\\n\";\n this.exampleSelector = fields.exampleSelector;\n this.prefix = fields.prefix ?? \"\";\n this.suffix = fields.suffix ?? \"\";\n this.templateFormat = fields.templateFormat ?? \"f-string\";\n this.validateTemplate = fields.validateTemplate ?? true;\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n /**\n * Formats the list of values and returns a list of formatted messages.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n const allValues = await this.mergePartialAndUserVariables(values);\n let examples = await this.getExamples(allValues);\n\n examples = examples.map((example) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n this.examplePrompt.inputVariables.forEach((inputVariable) => {\n result[inputVariable] = example[inputVariable];\n });\n return result;\n });\n\n const messages: BaseMessage[] = [];\n for (const example of examples) {\n const exampleMessages = await this.examplePrompt.formatMessages(example);\n messages.push(...exampleMessages);\n }\n return messages;\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n const exampleMessages = await Promise.all(\n examples.map((example) => this.examplePrompt.formatMessages(example))\n );\n const exampleStrings = exampleMessages\n .flat()\n .map((message) => message.content);\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n /**\n * Partially formats the prompt with the given values.\n * @param values The values to partially format the prompt with.\n * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted.\n */\n async partial(\n values: PartialValues<PartialVariableName>\n ): Promise<FewShotChatMessagePromptTemplate<RunInput, PartialVariableName>> {\n const newInputVariables = this.inputVariables.filter(\n (variable) => !(variable in values)\n ) as Exclude<Extract<keyof RunInput, string>, PartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | PartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotChatMessagePromptTemplate<\n InputValues<Exclude<Extract<keyof RunInput, string>, Partial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K,6BAA6B,OAAO;EACjE,MAAM,WAAW,MAAM,KAAK,YAAY,UAAU;EAClD,MAAM,kBAAkB,MAAM,QAAQ,IACpC,SAAS,IAAI,CAAC,YAAY,KAAK,cAAc,eAAe,QAAQ,CAAC,CACtE;EACD,MAAM,iBAAiB,gBACpB,MAAM,CACN,IAAI,CAAC,YAAY,QAAQ,QAAQ;EACpC,MAAM,WAAW;GAAC,KAAK;GAAQ,GAAG;GAAgB,KAAK;EAAO,EAAC,KAC7D,KAAK,iBACN;AACD,SAAO,eAAe,UAAU,KAAK,gBAAgB,UAAU;CAChE;;;;;;CAOD,MAAM,QACJG,QAC0E;EAC1E,MAAM,oBAAoB,KAAK,eAAe,OAC5C,CAAC,aAAa,EAAE,YAAY,QAC7B;EACD,MAAM,sBAAsB;GAC1B,GAAI,KAAK,oBAAoB,CAAE;GAC/B,GAAG;EACJ;EACD,MAAM,aAAa;GACjB,GAAG;GACH,gBAAgB;GAChB,kBAAkB;EACnB;AACD,SAAO,IAAI,iCAET;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"few_shot.js","names":["input: FewShotPromptTemplateInput","totalInputVariables: string[]","inputVariables: InputValues","values: PartialValues<NewPartialVariableName>","values: InputValues","data: SerializedFewShotTemplate","examples: Example[]","fields: FewShotChatMessagePromptTemplateInput","values: TypedPromptInputValues<RunInput>","result: Record<string, any>","messages: BaseMessage[]","values: PartialValues<PartialVariableName>"],"sources":["../../src/prompts/few_shot.ts"],"sourcesContent":["import { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n Example,\n} from \"./base.js\";\nimport type { BaseExampleSelector } from \"../example_selectors/base.js\";\nimport {\n type TemplateFormat,\n checkValidTemplate,\n renderTemplate,\n} from \"./template.js\";\nimport { PromptTemplate } from \"./prompt.js\";\nimport type { SerializedFewShotTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport type { BaseMessage } from \"../messages/index.js\";\nimport {\n BaseChatPromptTemplate,\n type BaseMessagePromptTemplate,\n} from \"./chat.js\";\n\nexport interface FewShotPromptTemplateInput\n extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector;\n\n /**\n * An {@link PromptTemplate} used to format a single example.\n */\n examplePrompt: PromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n */\n exampleSeparator?: string;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Prompt template that contains few-shot examples.\n * @augments BasePromptTemplate\n * @augments FewShotPromptTemplateInput\n * @example\n * ```typescript\n * const examplePrompt = PromptTemplate.fromTemplate(\n * \"Input: {input}\\nOutput: {output}\",\n * );\n *\n * const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples(\n * [\n * { input: \"happy\", output: \"sad\" },\n * { input: \"tall\", output: \"short\" },\n * { input: \"energetic\", output: \"lethargic\" },\n * { input: \"sunny\", output: \"gloomy\" },\n * { input: \"windy\", output: \"calm\" },\n * ],\n * new OpenAIEmbeddings(),\n * HNSWLib,\n * { k: 1 },\n * );\n *\n * const dynamicPrompt = new FewShotPromptTemplate({\n * exampleSelector,\n * examplePrompt,\n * prefix: \"Give the antonym of every input\",\n * suffix: \"Input: {adjective}\\nOutput:\",\n * inputVariables: [\"adjective\"],\n * });\n *\n * // Format the dynamic prompt with the input 'rainy'\n * console.log(await dynamicPrompt.format({ adjective: \"rainy\" }));\n *\n * ```\n */\nexport class FewShotPromptTemplate\n extends BaseStringPromptTemplate\n implements FewShotPromptTemplateInput\n{\n lc_serializable = false;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: PromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n constructor(input: FewShotPromptTemplateInput) {\n super(input);\n Object.assign(this, input);\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"few_shot\" {\n return \"few_shot\";\n }\n\n static lc_name() {\n return \"FewShotPromptTemplate\";\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n );\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n };\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotPromptTemplate(promptDict);\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: InputValues): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n\n const exampleStrings = await Promise.all(\n examples.map((example) => this.examplePrompt.format(example))\n );\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n serialize(): SerializedFewShotTemplate {\n if (this.exampleSelector || !this.examples) {\n throw new Error(\n \"Serializing an example selector is not currently supported\"\n );\n }\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Serializing an output parser is not currently supported\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n example_prompt: this.examplePrompt.serialize(),\n example_separator: this.exampleSeparator,\n suffix: this.suffix,\n prefix: this.prefix,\n template_format: this.templateFormat,\n examples: this.examples,\n };\n }\n\n static async deserialize(\n data: SerializedFewShotTemplate\n ): Promise<FewShotPromptTemplate> {\n const { example_prompt } = data;\n if (!example_prompt) {\n throw new Error(\"Missing example prompt\");\n }\n const examplePrompt = await PromptTemplate.deserialize(example_prompt);\n\n let examples: Example[];\n\n if (Array.isArray(data.examples)) {\n examples = data.examples;\n } else {\n throw new Error(\n \"Invalid examples format. Only list or string are supported.\"\n );\n }\n\n return new FewShotPromptTemplate({\n inputVariables: data.input_variables,\n examplePrompt,\n examples,\n exampleSeparator: data.example_separator,\n prefix: data.prefix,\n suffix: data.suffix,\n templateFormat: data.template_format,\n });\n }\n}\n\nexport interface FewShotChatMessagePromptTemplateInput\n extends BasePromptTemplateInput<InputValues> {\n /**\n * Examples to format into the prompt. Exactly one of this or\n * {@link exampleSelector} must be\n * provided.\n */\n examples?: Example[];\n\n /**\n * An {@link BaseMessagePromptTemplate} | {@link BaseChatPromptTemplate} used to format a single example.\n */\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n /**\n * String separator used to join the prefix, the examples, and suffix.\n *\n * @defaultValue `\"\\n\\n\"`\n */\n exampleSeparator?: string;\n\n /**\n * An {@link BaseExampleSelector} Examples to format into the prompt. Exactly one of this or\n * {@link examples} must be\n * provided.\n */\n exampleSelector?: BaseExampleSelector | undefined;\n\n /**\n * A prompt template string to put before the examples.\n *\n * @defaultValue `\"\"`\n */\n prefix?: string;\n\n /**\n * A prompt template string to put after the examples.\n *\n * @defaultValue `\"\"`\n */\n suffix?: string;\n\n /**\n * The format of the prompt template. Options are: 'f-string'\n *\n * @defaultValue `f-string`\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization.\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n}\n\n/**\n * Chat prompt template that contains few-shot examples.\n * @augments BasePromptTemplateInput\n * @augments FewShotChatMessagePromptTemplateInput\n */\nexport class FewShotChatMessagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n >\n extends BaseChatPromptTemplate\n implements FewShotChatMessagePromptTemplateInput\n{\n lc_serializable = true;\n\n examples?: InputValues[];\n\n exampleSelector?: BaseExampleSelector | undefined;\n\n examplePrompt: BaseMessagePromptTemplate | BaseChatPromptTemplate;\n\n suffix = \"\";\n\n exampleSeparator = \"\\n\\n\";\n\n prefix = \"\";\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n _getPromptType(): \"few_shot_chat\" {\n return \"few_shot_chat\";\n }\n\n static lc_name() {\n return \"FewShotChatMessagePromptTemplate\";\n }\n\n constructor(fields: FewShotChatMessagePromptTemplateInput) {\n super(fields);\n\n this.examples = fields.examples;\n this.examplePrompt = fields.examplePrompt;\n this.exampleSeparator = fields.exampleSeparator ?? \"\\n\\n\";\n this.exampleSelector = fields.exampleSelector;\n this.prefix = fields.prefix ?? \"\";\n this.suffix = fields.suffix ?? \"\";\n this.templateFormat = fields.templateFormat ?? \"f-string\";\n this.validateTemplate = fields.validateTemplate ?? true;\n\n if (this.examples !== undefined && this.exampleSelector !== undefined) {\n throw new Error(\n \"Only one of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.examples === undefined && this.exampleSelector === undefined) {\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.prefix + this.suffix,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n private async getExamples(\n inputVariables: InputValues\n ): Promise<InputValues[]> {\n if (this.examples !== undefined) {\n return this.examples;\n }\n if (this.exampleSelector !== undefined) {\n return this.exampleSelector.selectExamples(inputVariables);\n }\n\n throw new Error(\n \"One of 'examples' and 'example_selector' should be provided\"\n );\n }\n\n /**\n * Formats the list of values and returns a list of formatted messages.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async formatMessages(\n values: TypedPromptInputValues<RunInput>\n ): Promise<BaseMessage[]> {\n const allValues = await this.mergePartialAndUserVariables(values);\n let examples = await this.getExamples(allValues);\n\n examples = examples.map((example) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: Record<string, any> = {};\n this.examplePrompt.inputVariables.forEach((inputVariable) => {\n result[inputVariable] = example[inputVariable];\n });\n return result;\n });\n\n const messages: BaseMessage[] = [];\n for (const example of examples) {\n const exampleMessages = await this.examplePrompt.formatMessages(example);\n messages.push(...exampleMessages);\n }\n return messages;\n }\n\n /**\n * Formats the prompt with the given values.\n * @param values The values to format the prompt with.\n * @returns A promise that resolves to a string representing the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n const examples = await this.getExamples(allValues);\n const exampleMessages = await Promise.all(\n examples.map((example) => this.examplePrompt.formatMessages(example))\n );\n const exampleStrings = exampleMessages\n .flat()\n .map((message) => message.content);\n const template = [this.prefix, ...exampleStrings, this.suffix].join(\n this.exampleSeparator\n );\n return renderTemplate(template, this.templateFormat, allValues);\n }\n\n /**\n * Partially formats the prompt with the given values.\n * @param values The values to partially format the prompt with.\n * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted.\n */\n async partial(\n values: PartialValues<PartialVariableName>\n ): Promise<FewShotChatMessagePromptTemplate<RunInput, PartialVariableName>> {\n const newInputVariables = this.inputVariables.filter(\n (variable) => !(variable in values)\n ) as Exclude<Extract<keyof RunInput, string>, PartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | PartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new FewShotChatMessagePromptTemplate<\n InputValues<Exclude<Extract<keyof RunInput, string>, PartialVariableName>>\n >(promptDict);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,IAAa,wBAAb,MAAa,8BACH,yBAEV;CACE,kBAAkB;CAElB;CAEA;CAEA;CAEA,SAAS;CAET,mBAAmB;CAEnB,SAAS;CAET,iBAAiC;CAEjC,mBAAmB;CAEnB,YAAYA,OAAmC;EAC7C,MAAM,MAAM;EACZ,OAAO,OAAO,MAAM,MAAM;AAE1B,MAAI,KAAK,aAAa,UAAa,KAAK,oBAAoB,OAC1D,OAAM,IAAI,MACR;AAIJ,MAAI,KAAK,aAAa,UAAa,KAAK,oBAAoB,OAC1D,OAAM,IAAI,MACR;AAIJ,MAAI,KAAK,kBAAkB;GACzB,IAAIC,sBAAgC,KAAK;AACzC,OAAI,KAAK,kBACP,sBAAsB,oBAAoB,OACxC,OAAO,KAAK,KAAK,iBAAiB,CACnC;GAEH,mBACE,KAAK,SAAS,KAAK,QACnB,KAAK,gBACL,oBACD;EACF;CACF;CAED,iBAA6B;AAC3B,SAAO;CACR;CAED,OAAO,UAAU;AACf,SAAO;CACR;CAED,MAAc,YACZC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agePromptTemplateInput<RunInput, PartialVariableName>","totalInputVariables: string[]","checkValidTemplate","values: PartialValues<NewPartialVariableName>","values: TypedPromptInputValues<RunInput>","formatted: Record<string, any>","renderTemplate","output: ImageContent","ImagePromptValue"],"sources":["../../src/prompts/image.ts"],"sourcesContent":["import { MessageContent, ContentBlock } from \"../messages/index.js\";\nimport { ImagePromptValue, ImageContent } from \"../prompt_values.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport {\n BasePromptTemplate,\n BasePromptTemplateInput,\n TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n TemplateFormat,\n checkValidTemplate,\n renderTemplate,\n} from \"./template.js\";\n\n/**\n * Inputs to create a {@link ImagePromptTemplate}\n * @augments BasePromptTemplateInput\n */\nexport interface ImagePromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any
|
|
1
|
+
{"version":3,"file":"image.cjs","names":["BasePromptTemplate","input: ImagePromptTemplateInput<RunInput, PartialVariableName>","totalInputVariables: string[]","checkValidTemplate","values: PartialValues<NewPartialVariableName>","values: TypedPromptInputValues<RunInput>","formatted: Record<string, any>","renderTemplate","output: ImageContent","ImagePromptValue"],"sources":["../../src/prompts/image.ts"],"sourcesContent":["import { MessageContent, ContentBlock } from \"../messages/index.js\";\nimport { ImagePromptValue, ImageContent } from \"../prompt_values.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport {\n BasePromptTemplate,\n BasePromptTemplateInput,\n TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n TemplateFormat,\n checkValidTemplate,\n renderTemplate,\n} from \"./template.js\";\n\n/**\n * Inputs to create a {@link ImagePromptTemplate}\n * @augments BasePromptTemplateInput\n */\nexport interface ImagePromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n> extends BasePromptTemplateInput<RunInput, PartialVariableName> {\n /**\n * The prompt template\n */\n template: Record<string, unknown>;\n\n /**\n * The format of the prompt template. Options are 'f-string'\n *\n * @defaultValue 'f-string'\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n}\n\n/**\n * An image prompt template for a multimodal model.\n */\nexport class ImagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n> extends BasePromptTemplate<RunInput, ImagePromptValue, PartialVariableName> {\n static lc_name() {\n return \"ImagePromptTemplate\";\n }\n\n lc_namespace = [\"langchain_core\", \"prompts\", \"image\"];\n\n template: Record<string, unknown>;\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n\n constructor(input: ImagePromptTemplateInput<RunInput, PartialVariableName>) {\n super(input);\n this.template = input.template;\n this.templateFormat = input.templateFormat ?? this.templateFormat;\n this.validateTemplate = input.validateTemplate ?? this.validateTemplate;\n this.additionalContentFields = input.additionalContentFields;\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n [\n { type: \"image_url\", image_url: this.template },\n ] as unknown as MessageContent,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"prompt\" {\n return \"prompt\";\n }\n\n /**\n * Partially applies values to the prompt template.\n * @param values The values to be partially applied to the prompt template.\n * @returns A new instance of ImagePromptTemplate with the partially applied values.\n */\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n ) as Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | NewPartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new ImagePromptTemplate<\n InputValues<\n Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>\n >\n >(promptDict);\n }\n\n /**\n * Formats the prompt template with the provided values.\n * @param values The values to be used to format the prompt template.\n * @returns A promise that resolves to a string which is the formatted prompt.\n */\n async format<FormatOutput = ImageContent>(\n values: TypedPromptInputValues<RunInput>\n ): Promise<FormatOutput> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const formatted: Record<string, any> = {};\n for (const [key, value] of Object.entries(this.template)) {\n if (typeof value === \"string\") {\n formatted[key] = renderTemplate(value, this.templateFormat, values);\n } else {\n formatted[key] = value;\n }\n }\n const url = values.url || formatted.url;\n const detail = values.detail || formatted.detail;\n if (!url) {\n throw new Error(\"Must provide either an image URL.\");\n }\n if (typeof url !== \"string\") {\n throw new Error(\"url must be a string.\");\n }\n const output: ImageContent = { url };\n if (detail) {\n output.detail = detail;\n }\n return output as FormatOutput;\n }\n\n /**\n * Formats the prompt given the input values and returns a formatted\n * prompt value.\n * @param values The input values to format the prompt.\n * @returns A Promise that resolves to a formatted prompt value.\n */\n async formatPromptValue(\n values: TypedPromptInputValues<RunInput>\n ): Promise<ImagePromptValue> {\n const formattedPrompt = await this.format(values);\n return new ImagePromptValue(formattedPrompt);\n }\n}\n"],"mappings":";;;;;;;;AAsDA,IAAa,sBAAb,MAAa,4BAKHA,gCAAoE;CAC5E,OAAO,UAAU;AACf,SAAO;CACR;CAED,eAAe;EAAC;EAAkB;EAAW;CAAQ;CAErD;CAEA,iBAAiC;CAEjC,mBAAmB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AK,OAAO,OAAO;AACjD,SAAO,IAAII,uCAAiB;CAC7B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image.js","names":["input: ImagePromptTemplateInput<RunInput, PartialVariableName>","totalInputVariables: string[]","values: PartialValues<NewPartialVariableName>","values: TypedPromptInputValues<RunInput>","formatted: Record<string, any>","output: ImageContent"],"sources":["../../src/prompts/image.ts"],"sourcesContent":["import { MessageContent, ContentBlock } from \"../messages/index.js\";\nimport { ImagePromptValue, ImageContent } from \"../prompt_values.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport {\n BasePromptTemplate,\n BasePromptTemplateInput,\n TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n TemplateFormat,\n checkValidTemplate,\n renderTemplate,\n} from \"./template.js\";\n\n/**\n * Inputs to create a {@link ImagePromptTemplate}\n * @augments BasePromptTemplateInput\n */\nexport interface ImagePromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any
|
|
1
|
+
{"version":3,"file":"image.js","names":["input: ImagePromptTemplateInput<RunInput, PartialVariableName>","totalInputVariables: string[]","values: PartialValues<NewPartialVariableName>","values: TypedPromptInputValues<RunInput>","formatted: Record<string, any>","output: ImageContent"],"sources":["../../src/prompts/image.ts"],"sourcesContent":["import { MessageContent, ContentBlock } from \"../messages/index.js\";\nimport { ImagePromptValue, ImageContent } from \"../prompt_values.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport {\n BasePromptTemplate,\n BasePromptTemplateInput,\n TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n TemplateFormat,\n checkValidTemplate,\n renderTemplate,\n} from \"./template.js\";\n\n/**\n * Inputs to create a {@link ImagePromptTemplate}\n * @augments BasePromptTemplateInput\n */\nexport interface ImagePromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n> extends BasePromptTemplateInput<RunInput, PartialVariableName> {\n /**\n * The prompt template\n */\n template: Record<string, unknown>;\n\n /**\n * The format of the prompt template. Options are 'f-string'\n *\n * @defaultValue 'f-string'\n */\n templateFormat?: TemplateFormat;\n\n /**\n * Whether or not to try validating the template on initialization\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n}\n\n/**\n * An image prompt template for a multimodal model.\n */\nexport class ImagePromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n> extends BasePromptTemplate<RunInput, ImagePromptValue, PartialVariableName> {\n static lc_name() {\n return \"ImagePromptTemplate\";\n }\n\n lc_namespace = [\"langchain_core\", \"prompts\", \"image\"];\n\n template: Record<string, unknown>;\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n\n constructor(input: ImagePromptTemplateInput<RunInput, PartialVariableName>) {\n super(input);\n this.template = input.template;\n this.templateFormat = input.templateFormat ?? this.templateFormat;\n this.validateTemplate = input.validateTemplate ?? this.validateTemplate;\n this.additionalContentFields = input.additionalContentFields;\n\n if (this.validateTemplate) {\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n [\n { type: \"image_url\", image_url: this.template },\n ] as unknown as MessageContent,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"prompt\" {\n return \"prompt\";\n }\n\n /**\n * Partially applies values to the prompt template.\n * @param values The values to be partially applied to the prompt template.\n * @returns A new instance of ImagePromptTemplate with the partially applied values.\n */\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n ) as Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | NewPartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new ImagePromptTemplate<\n InputValues<\n Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>\n >\n >(promptDict);\n }\n\n /**\n * Formats the prompt template with the provided values.\n * @param values The values to be used to format the prompt template.\n * @returns A promise that resolves to a string which is the formatted prompt.\n */\n async format<FormatOutput = ImageContent>(\n values: TypedPromptInputValues<RunInput>\n ): Promise<FormatOutput> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const formatted: Record<string, any> = {};\n for (const [key, value] of Object.entries(this.template)) {\n if (typeof value === \"string\") {\n formatted[key] = renderTemplate(value, this.templateFormat, values);\n } else {\n formatted[key] = value;\n }\n }\n const url = values.url || formatted.url;\n const detail = values.detail || formatted.detail;\n if (!url) {\n throw new Error(\"Must provide either an image URL.\");\n }\n if (typeof url !== \"string\") {\n throw new Error(\"url must be a string.\");\n }\n const output: ImageContent = { url };\n if (detail) {\n output.detail = detail;\n }\n return output as FormatOutput;\n }\n\n /**\n * Formats the prompt given the input values and returns a formatted\n * prompt value.\n * @param values The input values to format the prompt.\n * @returns A Promise that resolves to a formatted prompt value.\n */\n async formatPromptValue(\n values: TypedPromptInputValues<RunInput>\n ): Promise<ImagePromptValue> {\n const formattedPrompt = await this.format(values);\n return new ImagePromptValue(formattedPrompt);\n }\n}\n"],"mappings":";;;;;;;;AAsDA,IAAa,sBAAb,MAAa,4BAKH,mBAAoE;CAC5E,OAAO,UAAU;AACf,SAAO;CACR;CAED,eAAe;EAAC;EAAkB;EAAW;CA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AC2B;EAC3B,MAAM,kBAAkB,MAAM,KAAK,OAAO,OAAO;AACjD,SAAO,IAAI,iBAAiB;CAC7B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipeline.cjs","names":["BasePromptTemplate","input: PipelinePromptTemplateInput<PromptTemplateType>","allValues: InputValues","requiredValueNames: string[]","values: InputValues","ChatPromptTemplate","values: PartialValues"],"sources":["../../src/prompts/pipeline.ts"],"sourcesContent":["import type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport type { SerializedBasePromptTemplate } from \"./serde.js\";\nimport { BasePromptTemplate, type BasePromptTemplateInput } from \"./base.js\";\nimport { ChatPromptTemplate } from \"./chat.js\";\n\n/**\n * Type that includes the name of the prompt and the prompt itself.\n */\nexport type PipelinePromptParams<\n PromptTemplateType extends BasePromptTemplate
|
|
1
|
+
{"version":3,"file":"pipeline.cjs","names":["BasePromptTemplate","input: PipelinePromptTemplateInput<PromptTemplateType>","allValues: InputValues","requiredValueNames: string[]","values: InputValues","ChatPromptTemplate","values: PartialValues"],"sources":["../../src/prompts/pipeline.ts"],"sourcesContent":["import type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport type { SerializedBasePromptTemplate } from \"./serde.js\";\nimport { BasePromptTemplate, type BasePromptTemplateInput } from \"./base.js\";\nimport { ChatPromptTemplate } from \"./chat.js\";\n\n/**\n * Type that includes the name of the prompt and the prompt itself.\n */\nexport type PipelinePromptParams<\n PromptTemplateType extends BasePromptTemplate,\n> = {\n name: string;\n prompt: PromptTemplateType;\n};\n\n/**\n * Type that extends the BasePromptTemplateInput type, excluding the\n * inputVariables property. It includes an array of pipelinePrompts and a\n * finalPrompt.\n */\nexport type PipelinePromptTemplateInput<\n PromptTemplateType extends BasePromptTemplate,\n> = Omit<BasePromptTemplateInput, \"inputVariables\"> & {\n pipelinePrompts: PipelinePromptParams<PromptTemplateType>[];\n finalPrompt: PromptTemplateType;\n};\n\n/**\n * Class that handles a sequence of prompts, each of which may require\n * different input variables. Includes methods for formatting these\n * prompts, extracting required input values, and handling partial\n * prompts.\n * @example\n * ```typescript\n * const composedPrompt = new PipelinePromptTemplate({\n * pipelinePrompts: [\n * {\n * name: \"introduction\",\n * prompt: PromptTemplate.fromTemplate(`You are impersonating {person}.`),\n * },\n * {\n * name: \"example\",\n * prompt: PromptTemplate.fromTemplate(\n * `Here's an example of an interaction:\n * Q: {example_q}\n * A: {example_a}`,\n * ),\n * },\n * {\n * name: \"start\",\n * prompt: PromptTemplate.fromTemplate(\n * `Now, do this for real!\n * Q: {input}\n * A:`,\n * ),\n * },\n * ],\n * finalPrompt: PromptTemplate.fromTemplate(\n * `{introduction}\n * {example}\n * {start}`,\n * ),\n * });\n *\n * const formattedPrompt = await composedPrompt.format({\n * person: \"Elon Musk\",\n * example_q: `What's your favorite car?`,\n * example_a: \"Tesla\",\n * input: `What's your favorite social media site?`,\n * });\n * ```\n */\nexport class PipelinePromptTemplate<\n PromptTemplateType extends BasePromptTemplate,\n> extends BasePromptTemplate {\n static lc_name() {\n return \"PipelinePromptTemplate\";\n }\n\n pipelinePrompts: PipelinePromptParams<PromptTemplateType>[];\n\n finalPrompt: PromptTemplateType;\n\n constructor(input: PipelinePromptTemplateInput<PromptTemplateType>) {\n super({ ...input, inputVariables: [] });\n this.pipelinePrompts = input.pipelinePrompts;\n this.finalPrompt = input.finalPrompt;\n this.inputVariables = this.computeInputValues();\n }\n\n /**\n * Computes the input values required by the pipeline prompts.\n * @returns Array of input values required by the pipeline prompts.\n */\n protected computeInputValues() {\n const intermediateValues = this.pipelinePrompts.map(\n (pipelinePrompt) => pipelinePrompt.name\n );\n const inputValues = this.pipelinePrompts\n .map((pipelinePrompt) =>\n pipelinePrompt.prompt.inputVariables.filter(\n (inputValue) => !intermediateValues.includes(inputValue)\n )\n )\n .flat();\n return [...new Set(inputValues)];\n }\n\n protected static extractRequiredInputValues(\n allValues: InputValues,\n requiredValueNames: string[]\n ) {\n return requiredValueNames.reduce((requiredValues, valueName) => {\n requiredValues[valueName] = allValues[valueName];\n return requiredValues;\n }, {} as InputValues);\n }\n\n /**\n * Formats the pipeline prompts based on the provided input values.\n * @param values Input values to format the pipeline prompts.\n * @returns Promise that resolves with the formatted input values.\n */\n protected async formatPipelinePrompts(\n values: InputValues\n ): Promise<InputValues> {\n const allValues = await this.mergePartialAndUserVariables(values);\n for (const { name: pipelinePromptName, prompt: pipelinePrompt } of this\n .pipelinePrompts) {\n const pipelinePromptInputValues =\n PipelinePromptTemplate.extractRequiredInputValues(\n allValues,\n pipelinePrompt.inputVariables\n );\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (pipelinePrompt instanceof ChatPromptTemplate) {\n allValues[pipelinePromptName] = await pipelinePrompt.formatMessages(\n pipelinePromptInputValues\n );\n } else {\n allValues[pipelinePromptName] = await pipelinePrompt.format(\n pipelinePromptInputValues\n );\n }\n }\n return PipelinePromptTemplate.extractRequiredInputValues(\n allValues,\n this.finalPrompt.inputVariables\n );\n }\n\n /**\n * Formats the final prompt value based on the provided input values.\n * @param values Input values to format the final prompt value.\n * @returns Promise that resolves with the formatted final prompt value.\n */\n async formatPromptValue(\n values: InputValues\n ): Promise<PromptTemplateType[\"PromptValueReturnType\"]> {\n return this.finalPrompt.formatPromptValue(\n await this.formatPipelinePrompts(values)\n );\n }\n\n async format(values: InputValues): Promise<string> {\n return this.finalPrompt.format(await this.formatPipelinePrompts(values));\n }\n\n /**\n * Handles partial prompts, which are prompts that have been partially\n * filled with input values.\n * @param values Partial input values.\n * @returns Promise that resolves with a new PipelinePromptTemplate instance with updated input variables.\n */\n async partial(\n values: PartialValues\n ): Promise<PipelinePromptTemplate<PromptTemplateType>> {\n const promptDict = { ...this };\n promptDict.inputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n );\n promptDict.partialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n };\n return new PipelinePromptTemplate<PromptTemplateType>(promptDict);\n }\n\n serialize(): SerializedBasePromptTemplate {\n throw new Error(\"Not implemented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,MAAM,KAAK,sBAAsB,OAAO,CACzC;CACF;CAED,MAAM,OAAOA,QAAsC;AACjD,SAAO,KAAK,YAAY,OAAO,MAAM,KAAK,sBAAsB,OAAO,CAAC;CACzE;;;;;;;CAQD,MAAM,QACJE,QACqD;EACrD,MAAM,aAAa,EAAE,GAAG,KAAM;EAC9B,WAAW,iBAAiB,KAAK,eAAe,OAC9C,CAAC,OAAO,EAAE,MAAM,QACjB;EACD,WAAW,mBAAmB;GAC5B,GAAI,KAAK,oBAAoB,CAAE;GAC/B,GAAG;EACJ;AACD,SAAO,IAAI,uBAA2C;CACvD;CAED,YAA0C;AACxC,QAAM,IAAI,MAAM;CACjB;CAED,iBAAyB;AACvB,SAAO;CACR;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipeline.js","names":["input: PipelinePromptTemplateInput<PromptTemplateType>","allValues: InputValues","requiredValueNames: string[]","values: InputValues","values: PartialValues"],"sources":["../../src/prompts/pipeline.ts"],"sourcesContent":["import type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport type { SerializedBasePromptTemplate } from \"./serde.js\";\nimport { BasePromptTemplate, type BasePromptTemplateInput } from \"./base.js\";\nimport { ChatPromptTemplate } from \"./chat.js\";\n\n/**\n * Type that includes the name of the prompt and the prompt itself.\n */\nexport type PipelinePromptParams<\n PromptTemplateType extends BasePromptTemplate
|
|
1
|
+
{"version":3,"file":"pipeline.js","names":["input: PipelinePromptTemplateInput<PromptTemplateType>","allValues: InputValues","requiredValueNames: string[]","values: InputValues","values: PartialValues"],"sources":["../../src/prompts/pipeline.ts"],"sourcesContent":["import type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport type { SerializedBasePromptTemplate } from \"./serde.js\";\nimport { BasePromptTemplate, type BasePromptTemplateInput } from \"./base.js\";\nimport { ChatPromptTemplate } from \"./chat.js\";\n\n/**\n * Type that includes the name of the prompt and the prompt itself.\n */\nexport type PipelinePromptParams<\n PromptTemplateType extends BasePromptTemplate,\n> = {\n name: string;\n prompt: PromptTemplateType;\n};\n\n/**\n * Type that extends the BasePromptTemplateInput type, excluding the\n * inputVariables property. It includes an array of pipelinePrompts and a\n * finalPrompt.\n */\nexport type PipelinePromptTemplateInput<\n PromptTemplateType extends BasePromptTemplate,\n> = Omit<BasePromptTemplateInput, \"inputVariables\"> & {\n pipelinePrompts: PipelinePromptParams<PromptTemplateType>[];\n finalPrompt: PromptTemplateType;\n};\n\n/**\n * Class that handles a sequence of prompts, each of which may require\n * different input variables. Includes methods for formatting these\n * prompts, extracting required input values, and handling partial\n * prompts.\n * @example\n * ```typescript\n * const composedPrompt = new PipelinePromptTemplate({\n * pipelinePrompts: [\n * {\n * name: \"introduction\",\n * prompt: PromptTemplate.fromTemplate(`You are impersonating {person}.`),\n * },\n * {\n * name: \"example\",\n * prompt: PromptTemplate.fromTemplate(\n * `Here's an example of an interaction:\n * Q: {example_q}\n * A: {example_a}`,\n * ),\n * },\n * {\n * name: \"start\",\n * prompt: PromptTemplate.fromTemplate(\n * `Now, do this for real!\n * Q: {input}\n * A:`,\n * ),\n * },\n * ],\n * finalPrompt: PromptTemplate.fromTemplate(\n * `{introduction}\n * {example}\n * {start}`,\n * ),\n * });\n *\n * const formattedPrompt = await composedPrompt.format({\n * person: \"Elon Musk\",\n * example_q: `What's your favorite car?`,\n * example_a: \"Tesla\",\n * input: `What's your favorite social media site?`,\n * });\n * ```\n */\nexport class PipelinePromptTemplate<\n PromptTemplateType extends BasePromptTemplate,\n> extends BasePromptTemplate {\n static lc_name() {\n return \"PipelinePromptTemplate\";\n }\n\n pipelinePrompts: PipelinePromptParams<PromptTemplateType>[];\n\n finalPrompt: PromptTemplateType;\n\n constructor(input: PipelinePromptTemplateInput<PromptTemplateType>) {\n super({ ...input, inputVariables: [] });\n this.pipelinePrompts = input.pipelinePrompts;\n this.finalPrompt = input.finalPrompt;\n this.inputVariables = this.computeInputValues();\n }\n\n /**\n * Computes the input values required by the pipeline prompts.\n * @returns Array of input values required by the pipeline prompts.\n */\n protected computeInputValues() {\n const intermediateValues = this.pipelinePrompts.map(\n (pipelinePrompt) => pipelinePrompt.name\n );\n const inputValues = this.pipelinePrompts\n .map((pipelinePrompt) =>\n pipelinePrompt.prompt.inputVariables.filter(\n (inputValue) => !intermediateValues.includes(inputValue)\n )\n )\n .flat();\n return [...new Set(inputValues)];\n }\n\n protected static extractRequiredInputValues(\n allValues: InputValues,\n requiredValueNames: string[]\n ) {\n return requiredValueNames.reduce((requiredValues, valueName) => {\n requiredValues[valueName] = allValues[valueName];\n return requiredValues;\n }, {} as InputValues);\n }\n\n /**\n * Formats the pipeline prompts based on the provided input values.\n * @param values Input values to format the pipeline prompts.\n * @returns Promise that resolves with the formatted input values.\n */\n protected async formatPipelinePrompts(\n values: InputValues\n ): Promise<InputValues> {\n const allValues = await this.mergePartialAndUserVariables(values);\n for (const { name: pipelinePromptName, prompt: pipelinePrompt } of this\n .pipelinePrompts) {\n const pipelinePromptInputValues =\n PipelinePromptTemplate.extractRequiredInputValues(\n allValues,\n pipelinePrompt.inputVariables\n );\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (pipelinePrompt instanceof ChatPromptTemplate) {\n allValues[pipelinePromptName] = await pipelinePrompt.formatMessages(\n pipelinePromptInputValues\n );\n } else {\n allValues[pipelinePromptName] = await pipelinePrompt.format(\n pipelinePromptInputValues\n );\n }\n }\n return PipelinePromptTemplate.extractRequiredInputValues(\n allValues,\n this.finalPrompt.inputVariables\n );\n }\n\n /**\n * Formats the final prompt value based on the provided input values.\n * @param values Input values to format the final prompt value.\n * @returns Promise that resolves with the formatted final prompt value.\n */\n async formatPromptValue(\n values: InputValues\n ): Promise<PromptTemplateType[\"PromptValueReturnType\"]> {\n return this.finalPrompt.formatPromptValue(\n await this.formatPipelinePrompts(values)\n );\n }\n\n async format(values: InputValues): Promise<string> {\n return this.finalPrompt.format(await this.formatPipelinePrompts(values));\n }\n\n /**\n * Handles partial prompts, which are prompts that have been partially\n * filled with input values.\n * @param values Partial input values.\n * @returns Promise that resolves with a new PipelinePromptTemplate instance with updated input variables.\n */\n async partial(\n values: PartialValues\n ): Promise<PipelinePromptTemplate<PromptTemplateType>> {\n const promptDict = { ...this };\n promptDict.inputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n );\n promptDict.partialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n };\n return new PipelinePromptTemplate<PromptTemplateType>(promptDict);\n }\n\n serialize(): SerializedBasePromptTemplate {\n throw new Error(\"Not implemented.\");\n }\n\n _getPromptType(): string {\n return \"pipeline\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,IAAa,yBAAb,MAAa,+BAEH,mBAAmB;CAC3B,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA;CAEA,YAAYA,OAAwD;EAClE,MAAM;GAAE,GAAG;GAAO,gBAAgB,CAAE;EAAE,EAAC;EACvC,KAAK,kBAAkB,MAAM;EAC7B,KAAK,cAAc,MAAM;EACzB,KAAK,iBAAiB,KAAK,oBAAoB;CAChD;;;;;CAMD,AAAU,qBAAqB;EAC7B,MAAM,qBAAqB,KAAK,gBAAgB,IAC9C,CAAC,mBAAmB,eAAe,KACpC;EACD,MAAM,cAAc,KAAK,gBACtB,IAAI,CAAC,mBACJ,eAAe,OAAO,eAAe,OACnC,CAAC,eAAe,CAAC,mBAAmB,SAAS,WAAW,CACzD,CACF,CACA,MAAM;AACT,SAAO,CAAC,GAAG,IAAI,IAAI,YAAa;CACjC;CAED,OAAiB,2BACfC,WACAC,oBACA;AACA,SAAO,mBAAmB,OAAO,CAAC,gBAAgB,cAAc;GAC9D,eAAe,aAAa,UAAU;AACtC,UAAO;EACR,GAAE,CAAE,EAAgB;CACtB;;;;;;CAOD,MAAgB,sBACdC,QACsB;EACtB,MAAM,YAAY,MAAM,KAAK,6BAA6B,OAAO;AACjE,OAAK,MAAM,EAAE,MAAM,oBAAoB,QAAQ,gBAAgB,IAAI,KAChE,iBAAiB;GAClB,MAAM,4BACJ,uBAAuB,2BACrB,WACA,eAAe,eAChB;AAEH,OAAI,0BAA0B,oBAC5B,UAAU,sBAAsB,MAAM,eAAe,eACnD,0BACD;QAED,UAAU,sBAAsB,MAAM,eAAe,OACnD,0BACD;EAEJ;AACD,SAAO,uBAAuB,2BAC5B,WACA,KAAK,YAAY,eAClB;CACF;;;;;;CAOD,MAAM,kBACJA,QACsD;AACtD,SAAO,KAAK,YAAY,kBACtB,MAAM,KAAK,sBAAsB,OAAO,CACzC;CACF;CAED,MAAM,OAAOA,QAAsC;AACjD,SAAO,KAAK,YAAY,OAAO,MAAM,KAAK,sBAAsB,OAAO,CAAC;CACzE;;;;;;;CAQD,MAAM,QACJC,QACqD;EACrD,MAAM,aAAa,EAAE,GAAG,KAAM;EAC9B,WAAW,iBAAiB,KAAK,eAAe,OAC9C,CAAC,OAAO,EAAE,MAAM,QACjB;EACD,WAAW,mBAAmB;GAC5B,GAAI,KAAK,oBAAoB,CAAE;GAC/B,GAAG;EACJ;AACD,SAAO,IAAI,uBAA2C;CACvD;CAED,YAA0C;AACxC,QAAM,IAAI,MAAM;CACjB;CAED,iBAAyB;AACvB,SAAO;CACR;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.cjs","names":["BaseStringPromptTemplate","input: PromptTemplateInput<RunInput, PartialVariableName>","totalInputVariables: string[]","checkValidTemplate","values: TypedPromptInputValues<RunInput>","renderTemplate","examples: string[]","suffix: string","inputVariables: string[]","template: T","options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >","parseTemplate","values: PartialValues<NewPartialVariableName>","data: SerializedPromptTemplate"],"sources":["../../src/prompts/prompt.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n checkValidTemplate,\n parseTemplate,\n renderTemplate,\n type TemplateFormat,\n} from \"./template.js\";\nimport type { SerializedPromptTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport { MessageContent, ContentBlock } from \"../messages/index.js\";\n\n/**\n * Inputs to create a {@link PromptTemplate}\n * @augments BasePromptTemplateInput\n */\nexport interface PromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n Format extends TemplateFormat = TemplateFormat\n> extends BasePromptTemplateInput<RunInput, PartialVariableName> {\n /**\n * The prompt template\n */\n template: MessageContent;\n\n /**\n * The format of the prompt template. Options are \"f-string\" and \"mustache\"\n */\n templateFormat?: Format;\n\n /**\n * Whether or not to try validating the template on initialization\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n}\n\ntype NonAlphanumeric =\n | \" \"\n | \"\\t\"\n | \"\\n\"\n | \"\\r\"\n | '\"'\n | \"'\"\n | \"{\"\n | \"[\"\n | \"(\"\n | \"`\"\n | \":\"\n | \";\";\n\n/**\n * Recursive type to extract template parameters from a string.\n * @template T - The input string.\n * @template Result - The resulting array of extracted template parameters.\n */\ntype ExtractTemplateParamsRecursive<\n T extends string,\n Result extends string[] = []\n> = T extends `${string}{${infer Param}}${infer Rest}`\n ? Param extends `${NonAlphanumeric}${string}`\n ? ExtractTemplateParamsRecursive<Rest, Result> // for non-template variables that look like template variables e.g. see https://github.com/langchain-ai/langchainjs/blob/main/langchain/src/chains/query_constructor/prompt.ts\n : ExtractTemplateParamsRecursive<Rest, [...Result, Param]>\n : Result;\n\nexport type ParamsFromFString<T extends string> = {\n [Key in\n | ExtractTemplateParamsRecursive<T>[number]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (string & Record<never, never>)]: any;\n};\n\nexport type ExtractedFStringParams<\n T extends string,\n RunInput extends InputValues = Symbol\n> = RunInput extends Symbol ? ParamsFromFString<T> : RunInput;\n\n/**\n * Schema to represent a basic prompt for an LLM.\n * @augments BasePromptTemplate\n * @augments PromptTemplateInput\n *\n * @example\n * ```ts\n * import { PromptTemplate } from \"langchain/prompts\";\n *\n * const prompt = new PromptTemplate({\n * inputVariables: [\"foo\"],\n * template: \"Say {foo}\",\n * });\n * ```\n */\nexport class PromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any\n >\n extends BaseStringPromptTemplate<RunInput, PartialVariableName>\n implements PromptTemplateInput<RunInput, PartialVariableName>\n{\n static lc_name() {\n return \"PromptTemplate\";\n }\n\n template: MessageContent;\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n\n constructor(input: PromptTemplateInput<RunInput, PartialVariableName>) {\n super(input);\n // If input is mustache and validateTemplate is not defined, set it to false\n if (\n input.templateFormat === \"mustache\" &&\n input.validateTemplate === undefined\n ) {\n this.validateTemplate = false;\n }\n Object.assign(this, input);\n\n if (this.validateTemplate) {\n if (this.templateFormat === \"mustache\") {\n throw new Error(\"Mustache templates cannot be validated.\");\n }\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.template,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"prompt\" {\n return \"prompt\";\n }\n\n /**\n * Formats the prompt template with the provided values.\n * @param values The values to be used to format the prompt template.\n * @returns A promise that resolves to a string which is the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n return renderTemplate(\n this.template as string,\n this.templateFormat,\n allValues\n );\n }\n\n /**\n * Take examples in list format with prefix and suffix to create a prompt.\n *\n * Intended to be used a a way to dynamically create a prompt from examples.\n *\n * @param examples - List of examples to use in the prompt.\n * @param suffix - String to go after the list of examples. Should generally set up the user's input.\n * @param inputVariables - A list of variable names the final prompt template will expect\n * @param exampleSeparator - The separator to use in between examples\n * @param prefix - String that should go before any examples. Generally includes examples.\n *\n * @returns The final prompt template generated.\n */\n static fromExamples(\n examples: string[],\n suffix: string,\n inputVariables: string[],\n exampleSeparator = \"\\n\\n\",\n prefix = \"\"\n ) {\n const template = [prefix, ...examples, suffix].join(exampleSeparator);\n return new PromptTemplate({\n inputVariables,\n template,\n });\n }\n\n /**\n * Load prompt template from a template f-string\n */\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"f-string\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"mustache\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<InputValues>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput> | InputValues> {\n const { templateFormat = \"f-string\", ...rest } = options ?? {};\n const names = new Set<string>();\n parseTemplate(template, templateFormat).forEach((node) => {\n if (node.type === \"variable\") {\n names.add(node.name);\n }\n });\n\n return new PromptTemplate({\n // Rely on extracted types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputVariables: [...names] as any[],\n templateFormat,\n template,\n ...rest,\n });\n }\n\n /**\n * Partially applies values to the prompt template.\n * @param values The values to be partially applied to the prompt template.\n * @returns A new instance of PromptTemplate with the partially applied values.\n */\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n ) as Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | NewPartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new PromptTemplate<\n InputValues<\n Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>\n >\n >(promptDict);\n }\n\n serialize(): SerializedPromptTemplate {\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Cannot serialize a prompt template with an output parser\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n template: this.template,\n template_format: this.templateFormat,\n };\n }\n\n static async deserialize(\n data: SerializedPromptTemplate\n ): Promise<PromptTemplate> {\n if (!data.template) {\n throw new Error(\"Prompt template must have a template\");\n }\n const res = new PromptTemplate({\n inputVariables: data.input_variables,\n template: data.template,\n templateFormat: data.template_format,\n });\n return res;\n }\n\n // TODO(from file)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6GA,IAAa,iBAAb,MAAa,uBAMHA,wCAEV;CACE,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA,iBAAiC;CAEjC,mBAAmB;;;;;;CAOnB;CAEA,YAAYC,OAA2D;EACrE,MAAM,MAAM;AAEZ,MACE,MAAM,mBAAmB,cACzB,MAAM,qBAAqB,QAE3B,KAAK,mBAAmB;EAE1B,OAAO,OAAO,MAAM,MAAM;A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I,MACR;AAGJ,SAAO;GACL,OAAO,KAAK,gBAAgB;GAC5B,iBAAiB,KAAK;GACtB,UAAU,KAAK;GACf,iBAAiB,KAAK;EACvB;CACF;CAED,aAAa,YACXC,MACyB;AACzB,MAAI,CAAC,KAAK,SACR,OAAM,IAAI,MAAM;EAElB,MAAM,MAAM,IAAI,eAAe;GAC7B,gBAAgB,KAAK;GACrB,UAAU,KAAK;GACf,gBAAgB,KAAK;EACtB;AACD,SAAO;CACR;AAGF"}
|
|
1
|
+
{"version":3,"file":"prompt.cjs","names":["BaseStringPromptTemplate","input: PromptTemplateInput<RunInput, PartialVariableName>","totalInputVariables: string[]","checkValidTemplate","values: TypedPromptInputValues<RunInput>","renderTemplate","examples: string[]","suffix: string","inputVariables: string[]","template: T","options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >","parseTemplate","values: PartialValues<NewPartialVariableName>","data: SerializedPromptTemplate"],"sources":["../../src/prompts/prompt.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n checkValidTemplate,\n parseTemplate,\n renderTemplate,\n type TemplateFormat,\n} from \"./template.js\";\nimport type { SerializedPromptTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport { MessageContent, ContentBlock } from \"../messages/index.js\";\n\n/**\n * Inputs to create a {@link PromptTemplate}\n * @augments BasePromptTemplateInput\n */\nexport interface PromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n Format extends TemplateFormat = TemplateFormat,\n> extends BasePromptTemplateInput<RunInput, PartialVariableName> {\n /**\n * The prompt template\n */\n template: MessageContent;\n\n /**\n * The format of the prompt template. Options are \"f-string\" and \"mustache\"\n */\n templateFormat?: Format;\n\n /**\n * Whether or not to try validating the template on initialization\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n}\n\ntype NonAlphanumeric =\n | \" \"\n | \"\\t\"\n | \"\\n\"\n | \"\\r\"\n | '\"'\n | \"'\"\n | \"{\"\n | \"[\"\n | \"(\"\n | \"`\"\n | \":\"\n | \";\";\n\n/**\n * Recursive type to extract template parameters from a string.\n * @template T - The input string.\n * @template Result - The resulting array of extracted template parameters.\n */\ntype ExtractTemplateParamsRecursive<\n T extends string,\n Result extends string[] = [],\n> = T extends `${string}{${infer Param}}${infer Rest}`\n ? Param extends `${NonAlphanumeric}${string}`\n ? ExtractTemplateParamsRecursive<Rest, Result> // for non-template variables that look like template variables e.g. see https://github.com/langchain-ai/langchainjs/blob/main/langchain/src/chains/query_constructor/prompt.ts\n : ExtractTemplateParamsRecursive<Rest, [...Result, Param]>\n : Result;\n\nexport type ParamsFromFString<T extends string> = {\n [Key in\n | ExtractTemplateParamsRecursive<T>[number]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (string & Record<never, never>)]: any;\n};\n\nexport type ExtractedFStringParams<\n T extends string,\n RunInput extends InputValues = Symbol,\n> = RunInput extends Symbol ? ParamsFromFString<T> : RunInput;\n\n/**\n * Schema to represent a basic prompt for an LLM.\n * @augments BasePromptTemplate\n * @augments PromptTemplateInput\n *\n * @example\n * ```ts\n * import { PromptTemplate } from \"langchain/prompts\";\n *\n * const prompt = new PromptTemplate({\n * inputVariables: [\"foo\"],\n * template: \"Say {foo}\",\n * });\n * ```\n */\nexport class PromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n >\n extends BaseStringPromptTemplate<RunInput, PartialVariableName>\n implements PromptTemplateInput<RunInput, PartialVariableName>\n{\n static lc_name() {\n return \"PromptTemplate\";\n }\n\n template: MessageContent;\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n\n constructor(input: PromptTemplateInput<RunInput, PartialVariableName>) {\n super(input);\n // If input is mustache and validateTemplate is not defined, set it to false\n if (\n input.templateFormat === \"mustache\" &&\n input.validateTemplate === undefined\n ) {\n this.validateTemplate = false;\n }\n Object.assign(this, input);\n\n if (this.validateTemplate) {\n if (this.templateFormat === \"mustache\") {\n throw new Error(\"Mustache templates cannot be validated.\");\n }\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.template,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"prompt\" {\n return \"prompt\";\n }\n\n /**\n * Formats the prompt template with the provided values.\n * @param values The values to be used to format the prompt template.\n * @returns A promise that resolves to a string which is the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n return renderTemplate(\n this.template as string,\n this.templateFormat,\n allValues\n );\n }\n\n /**\n * Take examples in list format with prefix and suffix to create a prompt.\n *\n * Intended to be used a a way to dynamically create a prompt from examples.\n *\n * @param examples - List of examples to use in the prompt.\n * @param suffix - String to go after the list of examples. Should generally set up the user's input.\n * @param inputVariables - A list of variable names the final prompt template will expect\n * @param exampleSeparator - The separator to use in between examples\n * @param prefix - String that should go before any examples. Generally includes examples.\n *\n * @returns The final prompt template generated.\n */\n static fromExamples(\n examples: string[],\n suffix: string,\n inputVariables: string[],\n exampleSeparator = \"\\n\\n\",\n prefix = \"\"\n ) {\n const template = [prefix, ...examples, suffix].join(exampleSeparator);\n return new PromptTemplate({\n inputVariables,\n template,\n });\n }\n\n /**\n * Load prompt template from a template f-string\n */\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"f-string\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"mustache\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<InputValues>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput> | InputValues> {\n const { templateFormat = \"f-string\", ...rest } = options ?? {};\n const names = new Set<string>();\n parseTemplate(template, templateFormat).forEach((node) => {\n if (node.type === \"variable\") {\n names.add(node.name);\n }\n });\n\n return new PromptTemplate({\n // Rely on extracted types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputVariables: [...names] as any[],\n templateFormat,\n template,\n ...rest,\n });\n }\n\n /**\n * Partially applies values to the prompt template.\n * @param values The values to be partially applied to the prompt template.\n * @returns A new instance of PromptTemplate with the partially applied values.\n */\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n ) as Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | NewPartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new PromptTemplate<\n InputValues<\n Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>\n >\n >(promptDict);\n }\n\n serialize(): SerializedPromptTemplate {\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Cannot serialize a prompt template with an output parser\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n template: this.template,\n template_format: this.templateFormat,\n };\n }\n\n static async deserialize(\n data: SerializedPromptTemplate\n ): Promise<PromptTemplate> {\n if (!data.template) {\n throw new Error(\"Prompt template must have a template\");\n }\n const res = new PromptTemplate({\n inputVariables: data.input_variables,\n template: data.template,\n templateFormat: data.template_format,\n });\n return res;\n }\n\n // TODO(from file)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6GA,IAAa,iBAAb,MAAa,uBAMHA,wCAEV;CACE,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA,iBAAiC;CAEjC,mBAAmB;;;;;;CAOnB;CAEA,YAAYC,OAA2D;EACrE,MAAM,MAAM;AAEZ,MACE,MAAM,mBAAmB,cACzB,MAAM,qBAAqB,QAE3B,KAAK,mBAAmB;EAE1B,OAAO,OAAO,MAAM,MAAM;AAE1B,MAAI,KAAK,kBAAkB;AACzB,OAAI,KAAK,mBAAmB,WAC1B,OAAM,IAAI,MAAM;GAElB,IAAIC,sBAAgC,KAAK;AACzC,OAAI,KAAK,kBACP,sBAAsB,oBAAoB,OACxC,OAAO,KAAK,KAAK,iBAAiB,CACnC;GAEHC,oCACE,KAAK,UACL,KAAK,gBACL,oBACD;EACF;CACF;CAED,iBAA2B;AACzB,SAAO;CACR;;;;;;CAOD,MAAM,OAAOC,QAA2D;EACtE,MAAM,YAAY,MAAM,KAAK,6BAA6B,OAAO;AACjE,SAAOC,gCACL,KAAK,UACL,KAAK,gBACL,UACD;CACF;;;;;;;;;;;;;;CAeD,OAAO,aACLC,UACAC,QACAC,gBACA,mBAAmB,QACnB,SAAS,IACT;EACA,MAAM,WAAW;GAAC;GAAQ,GAAG;GAAU;EAAO,EAAC,KAAK,iBAAiB;AACrE,SAAO,IAAI,eAAe;GACxB;GACA;EACD;CACF;CAsCD,OAAO,aAILC,UACAC,SAImE;EACnE,MAAM,EAAE,iBAAiB,WAAY,GAAG,MAAM,GAAG,WAAW,CAAE;EAC9D,MAAM,wBAAQ,IAAI;EAClBC,+BAAc,UAAU,eAAe,CAAC,QAAQ,CAAC,SAAS;AACxD,OAAI,KAAK,SAAS,YAChB,MAAM,IAAI,KAAK,KAAK;EAEvB,EAAC;AAEF,SAAO,IAAI,eAAe;GAGxB,gBAAgB,CAAC,GAAG,KAAM;GAC1B;GACA;GACA,GAAG;EACJ;CACF;;;;;;CAOD,MAAM,QACJC,QACA;EACA,MAAM,oBAAoB,KAAK,eAAe,OAC5C,CAAC,OAAO,EAAE,MAAM,QACjB;EACD,MAAM,sBAAsB;GAC1B,GAAI,KAAK,oBAAoB,CAAE;GAC/B,GAAG;EACJ;EACD,MAAM,aAAa;GACjB,GAAG;GACH,gBAAgB;GAChB,kBAAkB;EACnB;AACD,SAAO,IAAI,eAIT;CACH;CAED,YAAsC;AACpC,MAAI,KAAK,iBAAiB,OACxB,OAAM,IAAI,MACR;AAGJ,SAAO;GACL,OAAO,KAAK,gBAAgB;GAC5B,iBAAiB,KAAK;GACtB,UAAU,KAAK;GACf,iBAAiB,KAAK;EACvB;CACF;CAED,aAAa,YACXC,MACyB;AACzB,MAAI,CAAC,KAAK,SACR,OAAM,IAAI,MAAM;EAElB,MAAM,MAAM,IAAI,eAAe;GAC7B,gBAAgB,KAAK;GACrB,UAAU,KAAK;GACf,gBAAgB,KAAK;EACtB;AACD,SAAO;CACR;AAGF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.js","names":["input: PromptTemplateInput<RunInput, PartialVariableName>","totalInputVariables: string[]","values: TypedPromptInputValues<RunInput>","examples: string[]","suffix: string","inputVariables: string[]","template: T","options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >","values: PartialValues<NewPartialVariableName>","data: SerializedPromptTemplate"],"sources":["../../src/prompts/prompt.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n checkValidTemplate,\n parseTemplate,\n renderTemplate,\n type TemplateFormat,\n} from \"./template.js\";\nimport type { SerializedPromptTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport { MessageContent, ContentBlock } from \"../messages/index.js\";\n\n/**\n * Inputs to create a {@link PromptTemplate}\n * @augments BasePromptTemplateInput\n */\nexport interface PromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n Format extends TemplateFormat = TemplateFormat\n> extends BasePromptTemplateInput<RunInput, PartialVariableName> {\n /**\n * The prompt template\n */\n template: MessageContent;\n\n /**\n * The format of the prompt template. Options are \"f-string\" and \"mustache\"\n */\n templateFormat?: Format;\n\n /**\n * Whether or not to try validating the template on initialization\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n}\n\ntype NonAlphanumeric =\n | \" \"\n | \"\\t\"\n | \"\\n\"\n | \"\\r\"\n | '\"'\n | \"'\"\n | \"{\"\n | \"[\"\n | \"(\"\n | \"`\"\n | \":\"\n | \";\";\n\n/**\n * Recursive type to extract template parameters from a string.\n * @template T - The input string.\n * @template Result - The resulting array of extracted template parameters.\n */\ntype ExtractTemplateParamsRecursive<\n T extends string,\n Result extends string[] = []\n> = T extends `${string}{${infer Param}}${infer Rest}`\n ? Param extends `${NonAlphanumeric}${string}`\n ? ExtractTemplateParamsRecursive<Rest, Result> // for non-template variables that look like template variables e.g. see https://github.com/langchain-ai/langchainjs/blob/main/langchain/src/chains/query_constructor/prompt.ts\n : ExtractTemplateParamsRecursive<Rest, [...Result, Param]>\n : Result;\n\nexport type ParamsFromFString<T extends string> = {\n [Key in\n | ExtractTemplateParamsRecursive<T>[number]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (string & Record<never, never>)]: any;\n};\n\nexport type ExtractedFStringParams<\n T extends string,\n RunInput extends InputValues = Symbol\n> = RunInput extends Symbol ? ParamsFromFString<T> : RunInput;\n\n/**\n * Schema to represent a basic prompt for an LLM.\n * @augments BasePromptTemplate\n * @augments PromptTemplateInput\n *\n * @example\n * ```ts\n * import { PromptTemplate } from \"langchain/prompts\";\n *\n * const prompt = new PromptTemplate({\n * inputVariables: [\"foo\"],\n * template: \"Say {foo}\",\n * });\n * ```\n */\nexport class PromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any\n >\n extends BaseStringPromptTemplate<RunInput, PartialVariableName>\n implements PromptTemplateInput<RunInput, PartialVariableName>\n{\n static lc_name() {\n return \"PromptTemplate\";\n }\n\n template: MessageContent;\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n\n constructor(input: PromptTemplateInput<RunInput, PartialVariableName>) {\n super(input);\n // If input is mustache and validateTemplate is not defined, set it to false\n if (\n input.templateFormat === \"mustache\" &&\n input.validateTemplate === undefined\n ) {\n this.validateTemplate = false;\n }\n Object.assign(this, input);\n\n if (this.validateTemplate) {\n if (this.templateFormat === \"mustache\") {\n throw new Error(\"Mustache templates cannot be validated.\");\n }\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.template,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"prompt\" {\n return \"prompt\";\n }\n\n /**\n * Formats the prompt template with the provided values.\n * @param values The values to be used to format the prompt template.\n * @returns A promise that resolves to a string which is the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n return renderTemplate(\n this.template as string,\n this.templateFormat,\n allValues\n );\n }\n\n /**\n * Take examples in list format with prefix and suffix to create a prompt.\n *\n * Intended to be used a a way to dynamically create a prompt from examples.\n *\n * @param examples - List of examples to use in the prompt.\n * @param suffix - String to go after the list of examples. Should generally set up the user's input.\n * @param inputVariables - A list of variable names the final prompt template will expect\n * @param exampleSeparator - The separator to use in between examples\n * @param prefix - String that should go before any examples. Generally includes examples.\n *\n * @returns The final prompt template generated.\n */\n static fromExamples(\n examples: string[],\n suffix: string,\n inputVariables: string[],\n exampleSeparator = \"\\n\\n\",\n prefix = \"\"\n ) {\n const template = [prefix, ...examples, suffix].join(exampleSeparator);\n return new PromptTemplate({\n inputVariables,\n template,\n });\n }\n\n /**\n * Load prompt template from a template f-string\n */\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"f-string\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"mustache\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<InputValues>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput> | InputValues> {\n const { templateFormat = \"f-string\", ...rest } = options ?? {};\n const names = new Set<string>();\n parseTemplate(template, templateFormat).forEach((node) => {\n if (node.type === \"variable\") {\n names.add(node.name);\n }\n });\n\n return new PromptTemplate({\n // Rely on extracted types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputVariables: [...names] as any[],\n templateFormat,\n template,\n ...rest,\n });\n }\n\n /**\n * Partially applies values to the prompt template.\n * @param values The values to be partially applied to the prompt template.\n * @returns A new instance of PromptTemplate with the partially applied values.\n */\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n ) as Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | NewPartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new PromptTemplate<\n InputValues<\n Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>\n >\n >(promptDict);\n }\n\n serialize(): SerializedPromptTemplate {\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Cannot serialize a prompt template with an output parser\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n template: this.template,\n template_format: this.templateFormat,\n };\n }\n\n static async deserialize(\n data: SerializedPromptTemplate\n ): Promise<PromptTemplate> {\n if (!data.template) {\n throw new Error(\"Prompt template must have a template\");\n }\n const res = new PromptTemplate({\n inputVariables: data.input_variables,\n template: data.template,\n templateFormat: data.template_format,\n });\n return res;\n }\n\n // TODO(from file)\n}\n"],"mappings":";;;;;;;;;;;;;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K,eAAe,OAC5C,CAAC,OAAO,EAAE,MAAM,QACjB;EACD,MAAM,sBAAsB;GAC1B,GAAI,KAAK,oBAAoB,CAAE;GAC/B,GAAG;EACJ;EACD,MAAM,aAAa;GACjB,GAAG;GACH,gBAAgB;GAChB,kBAAkB;EACnB;AACD,SAAO,IAAI,eAIT;CACH;CAED,YAAsC;AACpC,MAAI,KAAK,iBAAiB,OACxB,OAAM,IAAI,MACR;AAGJ,SAAO;GACL,OAAO,KAAK,gBAAgB;GAC5B,iBAAiB,KAAK;GACtB,UAAU,KAAK;GACf,iBAAiB,KAAK;EACvB;CACF;CAED,aAAa,YACXC,MACyB;AACzB,MAAI,CAAC,KAAK,SACR,OAAM,IAAI,MAAM;EAElB,MAAM,MAAM,IAAI,eAAe;GAC7B,gBAAgB,KAAK;GACrB,UAAU,KAAK;GACf,gBAAgB,KAAK;EACtB;AACD,SAAO;CACR;AAGF"}
|
|
1
|
+
{"version":3,"file":"prompt.js","names":["input: PromptTemplateInput<RunInput, PartialVariableName>","totalInputVariables: string[]","values: TypedPromptInputValues<RunInput>","examples: string[]","suffix: string","inputVariables: string[]","template: T","options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >","values: PartialValues<NewPartialVariableName>","data: SerializedPromptTemplate"],"sources":["../../src/prompts/prompt.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport { BaseStringPromptTemplate } from \"./string.js\";\nimport type {\n BasePromptTemplateInput,\n TypedPromptInputValues,\n} from \"./base.js\";\nimport {\n checkValidTemplate,\n parseTemplate,\n renderTemplate,\n type TemplateFormat,\n} from \"./template.js\";\nimport type { SerializedPromptTemplate } from \"./serde.js\";\nimport type { InputValues, PartialValues } from \"../utils/types/index.js\";\nimport { MessageContent, ContentBlock } from \"../messages/index.js\";\n\n/**\n * Inputs to create a {@link PromptTemplate}\n * @augments BasePromptTemplateInput\n */\nexport interface PromptTemplateInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n Format extends TemplateFormat = TemplateFormat,\n> extends BasePromptTemplateInput<RunInput, PartialVariableName> {\n /**\n * The prompt template\n */\n template: MessageContent;\n\n /**\n * The format of the prompt template. Options are \"f-string\" and \"mustache\"\n */\n templateFormat?: Format;\n\n /**\n * Whether or not to try validating the template on initialization\n *\n * @defaultValue `true`\n */\n validateTemplate?: boolean;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n}\n\ntype NonAlphanumeric =\n | \" \"\n | \"\\t\"\n | \"\\n\"\n | \"\\r\"\n | '\"'\n | \"'\"\n | \"{\"\n | \"[\"\n | \"(\"\n | \"`\"\n | \":\"\n | \";\";\n\n/**\n * Recursive type to extract template parameters from a string.\n * @template T - The input string.\n * @template Result - The resulting array of extracted template parameters.\n */\ntype ExtractTemplateParamsRecursive<\n T extends string,\n Result extends string[] = [],\n> = T extends `${string}{${infer Param}}${infer Rest}`\n ? Param extends `${NonAlphanumeric}${string}`\n ? ExtractTemplateParamsRecursive<Rest, Result> // for non-template variables that look like template variables e.g. see https://github.com/langchain-ai/langchainjs/blob/main/langchain/src/chains/query_constructor/prompt.ts\n : ExtractTemplateParamsRecursive<Rest, [...Result, Param]>\n : Result;\n\nexport type ParamsFromFString<T extends string> = {\n [Key in\n | ExtractTemplateParamsRecursive<T>[number]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | (string & Record<never, never>)]: any;\n};\n\nexport type ExtractedFStringParams<\n T extends string,\n RunInput extends InputValues = Symbol,\n> = RunInput extends Symbol ? ParamsFromFString<T> : RunInput;\n\n/**\n * Schema to represent a basic prompt for an LLM.\n * @augments BasePromptTemplate\n * @augments PromptTemplateInput\n *\n * @example\n * ```ts\n * import { PromptTemplate } from \"langchain/prompts\";\n *\n * const prompt = new PromptTemplate({\n * inputVariables: [\"foo\"],\n * template: \"Say {foo}\",\n * });\n * ```\n */\nexport class PromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n >\n extends BaseStringPromptTemplate<RunInput, PartialVariableName>\n implements PromptTemplateInput<RunInput, PartialVariableName>\n{\n static lc_name() {\n return \"PromptTemplate\";\n }\n\n template: MessageContent;\n\n templateFormat: TemplateFormat = \"f-string\";\n\n validateTemplate = true;\n\n /**\n * Additional fields which should be included inside\n * the message content array if using a complex message\n * content.\n */\n additionalContentFields?: ContentBlock;\n\n constructor(input: PromptTemplateInput<RunInput, PartialVariableName>) {\n super(input);\n // If input is mustache and validateTemplate is not defined, set it to false\n if (\n input.templateFormat === \"mustache\" &&\n input.validateTemplate === undefined\n ) {\n this.validateTemplate = false;\n }\n Object.assign(this, input);\n\n if (this.validateTemplate) {\n if (this.templateFormat === \"mustache\") {\n throw new Error(\"Mustache templates cannot be validated.\");\n }\n let totalInputVariables: string[] = this.inputVariables;\n if (this.partialVariables) {\n totalInputVariables = totalInputVariables.concat(\n Object.keys(this.partialVariables)\n );\n }\n checkValidTemplate(\n this.template,\n this.templateFormat,\n totalInputVariables\n );\n }\n }\n\n _getPromptType(): \"prompt\" {\n return \"prompt\";\n }\n\n /**\n * Formats the prompt template with the provided values.\n * @param values The values to be used to format the prompt template.\n * @returns A promise that resolves to a string which is the formatted prompt.\n */\n async format(values: TypedPromptInputValues<RunInput>): Promise<string> {\n const allValues = await this.mergePartialAndUserVariables(values);\n return renderTemplate(\n this.template as string,\n this.templateFormat,\n allValues\n );\n }\n\n /**\n * Take examples in list format with prefix and suffix to create a prompt.\n *\n * Intended to be used a a way to dynamically create a prompt from examples.\n *\n * @param examples - List of examples to use in the prompt.\n * @param suffix - String to go after the list of examples. Should generally set up the user's input.\n * @param inputVariables - A list of variable names the final prompt template will expect\n * @param exampleSeparator - The separator to use in between examples\n * @param prefix - String that should go before any examples. Generally includes examples.\n *\n * @returns The final prompt template generated.\n */\n static fromExamples(\n examples: string[],\n suffix: string,\n inputVariables: string[],\n exampleSeparator = \"\\n\\n\",\n prefix = \"\"\n ) {\n const template = [prefix, ...examples, suffix].join(exampleSeparator);\n return new PromptTemplate({\n inputVariables,\n template,\n });\n }\n\n /**\n * Load prompt template from a template f-string\n */\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"f-string\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput>>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, \"mustache\">,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<InputValues>;\n\n static fromTemplate<\n RunInput extends InputValues = Symbol,\n T extends string = string,\n >(\n template: T,\n options?: Omit<\n PromptTemplateInput<RunInput, string, TemplateFormat>,\n \"template\" | \"inputVariables\"\n >\n ): PromptTemplate<ExtractedFStringParams<T, RunInput> | InputValues> {\n const { templateFormat = \"f-string\", ...rest } = options ?? {};\n const names = new Set<string>();\n parseTemplate(template, templateFormat).forEach((node) => {\n if (node.type === \"variable\") {\n names.add(node.name);\n }\n });\n\n return new PromptTemplate({\n // Rely on extracted types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputVariables: [...names] as any[],\n templateFormat,\n template,\n ...rest,\n });\n }\n\n /**\n * Partially applies values to the prompt template.\n * @param values The values to be partially applied to the prompt template.\n * @returns A new instance of PromptTemplate with the partially applied values.\n */\n async partial<NewPartialVariableName extends string>(\n values: PartialValues<NewPartialVariableName>\n ) {\n const newInputVariables = this.inputVariables.filter(\n (iv) => !(iv in values)\n ) as Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>[];\n const newPartialVariables = {\n ...(this.partialVariables ?? {}),\n ...values,\n } as PartialValues<PartialVariableName | NewPartialVariableName>;\n const promptDict = {\n ...this,\n inputVariables: newInputVariables,\n partialVariables: newPartialVariables,\n };\n return new PromptTemplate<\n InputValues<\n Exclude<Extract<keyof RunInput, string>, NewPartialVariableName>\n >\n >(promptDict);\n }\n\n serialize(): SerializedPromptTemplate {\n if (this.outputParser !== undefined) {\n throw new Error(\n \"Cannot serialize a prompt template with an output parser\"\n );\n }\n return {\n _type: this._getPromptType(),\n input_variables: this.inputVariables,\n template: this.template,\n template_format: this.templateFormat,\n };\n }\n\n static async deserialize(\n data: SerializedPromptTemplate\n ): Promise<PromptTemplate> {\n if (!data.template) {\n throw new Error(\"Prompt template must have a template\");\n }\n const res = new PromptTemplate({\n inputVariables: data.input_variables,\n template: data.template,\n templateFormat: data.template_format,\n });\n return res;\n }\n\n // TODO(from file)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6GA,IAAa,iBAAb,MAAa,uBAMH,yBAEV;CACE,OAAO,UAAU;AACf,SAAO;CACR;CAED;CAEA,iBAAiC;CAEjC,mBAAmB;;;;;;CAOnB;CAEA,YAAYA,OAA2D;EACrE,MAAM,MAAM;AAEZ,MACE,MAAM,mBAAmB,cACzB,MAAM,qBAAqB,QAE3B,KAAK,mBAAmB;EAE1B,OAAO,OAAO,MAAM,MAAM;AAE1B,MAAI,KAAK,kBAAkB;AACzB,OAAI,KAAK,mBAAmB,WAC1B,OAAM,IAAI,MAAM;GAElB,IAAIC,sBAAgC,KAAK;AACzC,OAAI,KAAK,kBACP,sBAAsB,oBAAoB,OACxC,OAAO,KAAK,KAAK,iBAAiB,CACnC;GAEH,mBACE,KAAK,UACL,KAAK,gBACL,oBACD;EACF;CACF;CAED,iBAA2B;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GACf,gBAAgB,KAAK;EACtB;AACD,SAAO;CACR;AAGF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string.cjs","names":["BasePromptTemplate","values: TypedPromptInputValues<RunInput>","StringPromptValue"],"sources":["../../src/prompts/string.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport type { InputValues } from \"../utils/types/index.js\";\nimport {\n type StringPromptValueInterface,\n StringPromptValue,\n} from \"../prompt_values.js\";\nimport { BasePromptTemplate, type TypedPromptInputValues } from \"./base.js\";\n\n/**\n * Base class for string prompt templates. It extends the\n * BasePromptTemplate class and overrides the formatPromptValue method to\n * return a StringPromptValue.\n */\nexport abstract class BaseStringPromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any
|
|
1
|
+
{"version":3,"file":"string.cjs","names":["BasePromptTemplate","values: TypedPromptInputValues<RunInput>","StringPromptValue"],"sources":["../../src/prompts/string.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport type { InputValues } from \"../utils/types/index.js\";\nimport {\n type StringPromptValueInterface,\n StringPromptValue,\n} from \"../prompt_values.js\";\nimport { BasePromptTemplate, type TypedPromptInputValues } from \"./base.js\";\n\n/**\n * Base class for string prompt templates. It extends the\n * BasePromptTemplate class and overrides the formatPromptValue method to\n * return a StringPromptValue.\n */\nexport abstract class BaseStringPromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n> extends BasePromptTemplate<\n RunInput,\n StringPromptValueInterface,\n PartialVariableName\n> {\n /**\n * Formats the prompt given the input values and returns a formatted\n * prompt value.\n * @param values The input values to format the prompt.\n * @returns A Promise that resolves to a formatted prompt value.\n */\n async formatPromptValue(\n values: TypedPromptInputValues<RunInput>\n ): Promise<StringPromptValueInterface> {\n const formattedPrompt = await this.format(values);\n return new StringPromptValue(formattedPrompt);\n }\n}\n"],"mappings":";;;;;;;;;AAeA,IAAsB,2BAAtB,cAKUA,gCAIR;;;;;;;CAOA,MAAM,kBACJC,QACqC;EACrC,MAAM,kBAAkB,MAAM,KAAK,OAAO,OAAO;AACjD,SAAO,IAAIC,wCAAkB;CAC9B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string.js","names":["values: TypedPromptInputValues<RunInput>"],"sources":["../../src/prompts/string.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport type { InputValues } from \"../utils/types/index.js\";\nimport {\n type StringPromptValueInterface,\n StringPromptValue,\n} from \"../prompt_values.js\";\nimport { BasePromptTemplate, type TypedPromptInputValues } from \"./base.js\";\n\n/**\n * Base class for string prompt templates. It extends the\n * BasePromptTemplate class and overrides the formatPromptValue method to\n * return a StringPromptValue.\n */\nexport abstract class BaseStringPromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any
|
|
1
|
+
{"version":3,"file":"string.js","names":["values: TypedPromptInputValues<RunInput>"],"sources":["../../src/prompts/string.ts"],"sourcesContent":["// Default generic \"any\" values are for backwards compatibility.\n// Replace with \"string\" when we are comfortable with a breaking change.\n\nimport type { InputValues } from \"../utils/types/index.js\";\nimport {\n type StringPromptValueInterface,\n StringPromptValue,\n} from \"../prompt_values.js\";\nimport { BasePromptTemplate, type TypedPromptInputValues } from \"./base.js\";\n\n/**\n * Base class for string prompt templates. It extends the\n * BasePromptTemplate class and overrides the formatPromptValue method to\n * return a StringPromptValue.\n */\nexport abstract class BaseStringPromptTemplate<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n> extends BasePromptTemplate<\n RunInput,\n StringPromptValueInterface,\n PartialVariableName\n> {\n /**\n * Formats the prompt given the input values and returns a formatted\n * prompt value.\n * @param values The input values to format the prompt.\n * @returns A Promise that resolves to a formatted prompt value.\n */\n async formatPromptValue(\n values: TypedPromptInputValues<RunInput>\n ): Promise<StringPromptValueInterface> {\n const formattedPrompt = await this.format(values);\n return new StringPromptValue(formattedPrompt);\n }\n}\n"],"mappings":";;;;;;;;;AAeA,IAAsB,2BAAtB,cAKU,mBAIR;;;;;;;CAOA,MAAM,kBACJA,QACqC;EACrC,MAAM,kBAAkB,MAAM,KAAK,OAAO,OAAO;AACjD,SAAO,IAAI,kBAAkB;CAC9B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"structured.cjs","names":["x: unknown","ChatPromptTemplate","input: StructuredPromptInput<RunInput, PartialVariableName>","coerceable: RunnableLike<ChatPromptValueInterface, NewRunOutput>","RunnableBinding","promptMessages: (\n | ChatPromptTemplate<InputValues, string>\n | BaseMessagePromptTemplateLike\n )[]","schema: StructuredPromptInput[\"schema\"]","method?: \"jsonMode\" | \"jsonSchema\" | \"functionMode\""],"sources":["../../src/prompts/structured.ts"],"sourcesContent":["import { ChatPromptValueInterface } from \"../prompt_values.js\";\nimport { RunnableLike, Runnable, RunnableBinding } from \"../runnables/base.js\";\nimport { RunnableConfig } from \"../runnables/config.js\";\nimport { InputValues } from \"../utils/types/index.js\";\nimport {\n BaseMessagePromptTemplateLike,\n ChatPromptTemplate,\n ChatPromptTemplateInput,\n} from \"./chat.js\";\n\nfunction isWithStructuredOutput(x: unknown): x is {\n withStructuredOutput: (...arg: unknown[]) => Runnable;\n} {\n return (\n typeof x === \"object\" &&\n x != null &&\n \"withStructuredOutput\" in x &&\n typeof x.withStructuredOutput === \"function\"\n );\n}\n\nfunction isRunnableBinding(x: unknown): x is RunnableBinding<unknown, unknown> {\n return (\n typeof x === \"object\" &&\n x != null &&\n \"lc_id\" in x &&\n Array.isArray(x.lc_id) &&\n x.lc_id.join(\"/\") === \"langchain_core/runnables/RunnableBinding\"\n );\n}\n\n/**\n * Interface for the input of a ChatPromptTemplate.\n */\nexport interface StructuredPromptInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any
|
|
1
|
+
{"version":3,"file":"structured.cjs","names":["x: unknown","ChatPromptTemplate","input: StructuredPromptInput<RunInput, PartialVariableName>","coerceable: RunnableLike<ChatPromptValueInterface, NewRunOutput>","RunnableBinding","promptMessages: (\n | ChatPromptTemplate<InputValues, string>\n | BaseMessagePromptTemplateLike\n )[]","schema: StructuredPromptInput[\"schema\"]","method?: \"jsonMode\" | \"jsonSchema\" | \"functionMode\""],"sources":["../../src/prompts/structured.ts"],"sourcesContent":["import { ChatPromptValueInterface } from \"../prompt_values.js\";\nimport { RunnableLike, Runnable, RunnableBinding } from \"../runnables/base.js\";\nimport { RunnableConfig } from \"../runnables/config.js\";\nimport { InputValues } from \"../utils/types/index.js\";\nimport {\n BaseMessagePromptTemplateLike,\n ChatPromptTemplate,\n ChatPromptTemplateInput,\n} from \"./chat.js\";\n\nfunction isWithStructuredOutput(x: unknown): x is {\n withStructuredOutput: (...arg: unknown[]) => Runnable;\n} {\n return (\n typeof x === \"object\" &&\n x != null &&\n \"withStructuredOutput\" in x &&\n typeof x.withStructuredOutput === \"function\"\n );\n}\n\nfunction isRunnableBinding(x: unknown): x is RunnableBinding<unknown, unknown> {\n return (\n typeof x === \"object\" &&\n x != null &&\n \"lc_id\" in x &&\n Array.isArray(x.lc_id) &&\n x.lc_id.join(\"/\") === \"langchain_core/runnables/RunnableBinding\"\n );\n}\n\n/**\n * Interface for the input of a ChatPromptTemplate.\n */\nexport interface StructuredPromptInput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n> extends ChatPromptTemplateInput<RunInput, PartialVariableName> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schema: Record<string, any>;\n method?: \"jsonMode\" | \"jsonSchema\" | \"functionMode\";\n}\n\nexport class StructuredPrompt<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunInput extends InputValues = any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PartialVariableName extends string = any,\n >\n extends ChatPromptTemplate<RunInput, PartialVariableName>\n implements StructuredPromptInput<RunInput, PartialVariableName>\n{\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schema: Record<string, any>;\n\n method?: \"jsonMode\" | \"jsonSchema\" | \"functionMode\";\n\n lc_namespace = [\"langchain_core\", \"prompts\", \"structured\"];\n\n get lc_aliases(): Record<string, string> {\n return {\n ...super.lc_aliases,\n schema: \"schema_\",\n };\n }\n\n constructor(input: StructuredPromptInput<RunInput, PartialVariableName>) {\n super(input);\n this.schema = input.schema;\n this.method = input.method;\n }\n\n pipe<NewRunOutput>(\n coerceable: RunnableLike<ChatPromptValueInterface, NewRunOutput>\n ): Runnable<RunInput, Exclude<NewRunOutput, Error>, RunnableConfig> {\n if (isWithStructuredOutput(coerceable)) {\n return super.pipe(coerceable.withStructuredOutput(this.schema));\n }\n\n if (\n isRunnableBinding(coerceable) &&\n isWithStructuredOutput(coerceable.bound)\n ) {\n return super.pipe(\n new RunnableBinding({\n bound: coerceable.bound.withStructuredOutput(\n this.schema,\n ...(this.method ? [{ method: this.method }] : [])\n ),\n kwargs: coerceable.kwargs ?? {},\n config: coerceable.config,\n configFactories: coerceable.configFactories,\n })\n );\n }\n\n throw new Error(\n `Structured prompts need to be piped to a language model that supports the \"withStructuredOutput()\" method.`\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static fromMessagesAndSchema<RunInput extends InputValues = any>(\n promptMessages: (\n | ChatPromptTemplate<InputValues, string>\n | BaseMessagePromptTemplateLike\n )[],\n schema: StructuredPromptInput[\"schema\"],\n method?: \"jsonMode\" | \"jsonSchema\" | \"functionMode\"\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): ChatPromptTemplate<RunInput, any> {\n return StructuredPrompt.fromMessages<\n RunInput,\n StructuredPromptInput<RunInput>\n >(promptMessages, { schema, method });\n }\n}\n"],"mappings":";;;;AAUA,SAAS,uBAAuBA,GAE9B;AACA,QACE,OAAO,MAAM,YACb,KAAK,QACL,0BAA0B,KAC1B,OAAO,EAAE,yBAAyB;AAErC;AAED,SAAS,kBAAkBA,GAAoD;AAC7E,QACE,OAAO,MAAM,YACb,KAAK,QACL,WAAW,KACX,MAAM,QAAQ,EAAE,MAAM,IACtB,EAAE,MAAM,KAAK,IAAI,KAAK;AAEzB;AAgBD,IAAa,mBAAb,MAAa,yBAMHC,gCAEV;CAEE;CAEA;CAEA,eAAe;EAAC;EAAkB;EAAW;CAAa;CAE1D,IAAI,aAAqC;AACvC,SAAO;GACL,GAAG,MAAM;GACT,QAAQ;EACT;CACF;CAED,YAAYC,OAA6D;EACvE,MAAM,MAAM;EACZ,KAAK,SAAS,MAAM;EACpB,KAAK,SAAS,MAAM;CACrB;CAED,KACEC,YACkE;AAClE,MAAI,uBAAuB,WAAW,CACpC,QAAO,MAAM,KAAK,WAAW,qBAAqB,KAAK,OAAO,CAAC;AAGjE,MACE,kBAAkB,WAAW,IAC7B,uBAAuB,WAAW,MAAM,CAExC,QAAO,MAAM,KACX,IAAIC,6BAAgB;GAClB,OAAO,WAAW,MAAM,qBACtB,KAAK,QACL,GAAI,KAAK,SAAS,CAAC,EAAE,QAAQ,KAAK,OAAQ,CAAC,IAAG,CAAE,EACjD;GACD,QAAQ,WAAW,UAAU,CAAE;GAC/B,QAAQ,WAAW;GACnB,iBAAiB,WAAW;EAC7B,GACF;AAGH,QAAM,IAAI,MACR,CAAC,0GAA0G,CAAC;CAE/G;CAGD,OAAO,sBACLC,gBAIAC,QACAC,QAEmC;AACnC,SAAO,iBAAiB,aAGtB,gBAAgB;GAAE;GAAQ;EAAQ,EAAC;CACtC;AACF"}
|