@langchain/core 1.1.17 → 1.1.18
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 +15 -0
- package/dist/agents.d.ts.map +1 -1
- package/dist/caches/index.d.cts.map +1 -1
- package/dist/callbacks/base.d.cts.map +1 -1
- package/dist/errors/index.cjs +38 -0
- package/dist/errors/index.cjs.map +1 -1
- package/dist/errors/index.d.cts +27 -0
- package/dist/errors/index.d.cts.map +1 -0
- package/dist/errors/index.d.ts +27 -0
- package/dist/errors/index.d.ts.map +1 -0
- package/dist/errors/index.js +33 -1
- package/dist/errors/index.js.map +1 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.d.cts +1 -1
- package/dist/language_models/base.d.cts.map +1 -1
- package/dist/language_models/base.d.ts +1 -1
- package/dist/language_models/base.d.ts.map +1 -1
- package/dist/language_models/base.js.map +1 -1
- package/dist/language_models/chat_models.cjs +11 -0
- package/dist/language_models/chat_models.cjs.map +1 -1
- package/dist/language_models/chat_models.d.cts +4 -4
- package/dist/language_models/chat_models.d.cts.map +1 -1
- package/dist/language_models/chat_models.d.ts +4 -4
- package/dist/language_models/chat_models.d.ts.map +1 -1
- package/dist/language_models/chat_models.js +11 -0
- package/dist/language_models/chat_models.js.map +1 -1
- package/dist/language_models/llms.cjs.map +1 -1
- package/dist/language_models/llms.d.cts +4 -4
- package/dist/language_models/llms.d.cts.map +1 -1
- package/dist/language_models/llms.d.ts +4 -4
- package/dist/language_models/llms.d.ts.map +1 -1
- package/dist/language_models/llms.js.map +1 -1
- package/dist/load/import_map.cjs +2 -0
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +2 -0
- package/dist/load/import_map.js.map +1 -1
- package/dist/memory.d.cts.map +1 -1
- package/dist/messages/utils.cjs +2 -2
- package/dist/messages/utils.cjs.map +1 -1
- package/dist/output_parsers/base.cjs +2 -2
- package/dist/output_parsers/base.cjs.map +1 -1
- package/dist/prompts/chat.cjs +2 -2
- package/dist/prompts/chat.cjs.map +1 -1
- package/dist/prompts/template.cjs +2 -2
- package/dist/prompts/template.cjs.map +1 -1
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.d.cts +2 -2
- package/dist/runnables/base.d.cts.map +1 -1
- package/dist/runnables/base.d.ts +2 -2
- package/dist/runnables/base.d.ts.map +1 -1
- package/dist/runnables/base.js.map +1 -1
- package/package.json +12 -1
|
@@ -26,10 +26,10 @@ declare abstract class BaseLLM<CallOptions extends BaseLLMCallOptions = BaseLLMC
|
|
|
26
26
|
* @param options Options for the LLM call.
|
|
27
27
|
* @returns A string result based on the prompt.
|
|
28
28
|
*/
|
|
29
|
-
invoke(input: BaseLanguageModelInput, options?: CallOptions): Promise<string>;
|
|
29
|
+
invoke(input: BaseLanguageModelInput, options?: Partial<CallOptions>): Promise<string>;
|
|
30
30
|
_streamResponseChunks(_input: string, _options: this["ParsedCallOptions"], _runManager?: CallbackManagerForLLMRun): AsyncGenerator<GenerationChunk>;
|
|
31
31
|
protected _separateRunnableConfigFromCallOptionsCompat(options?: Partial<CallOptions>): [RunnableConfig, this["ParsedCallOptions"]];
|
|
32
|
-
_streamIterator(input: BaseLanguageModelInput, options?: CallOptions): AsyncGenerator<string>;
|
|
32
|
+
_streamIterator(input: BaseLanguageModelInput, options?: Partial<CallOptions>): AsyncGenerator<string>;
|
|
33
33
|
/**
|
|
34
34
|
* This method takes prompt values, options, and callbacks, and generates
|
|
35
35
|
* a result based on the prompts.
|
|
@@ -38,7 +38,7 @@ declare abstract class BaseLLM<CallOptions extends BaseLLMCallOptions = BaseLLMC
|
|
|
38
38
|
* @param callbacks Callbacks for the LLM call.
|
|
39
39
|
* @returns An LLMResult based on the prompts.
|
|
40
40
|
*/
|
|
41
|
-
generatePrompt(promptValues: BasePromptValueInterface[], options?: string[] | CallOptions
|
|
41
|
+
generatePrompt(promptValues: BasePromptValueInterface[], options?: string[] | Partial<CallOptions>, callbacks?: Callbacks): Promise<LLMResult>;
|
|
42
42
|
/**
|
|
43
43
|
* Run the LLM on the given prompts and input.
|
|
44
44
|
*/
|
|
@@ -71,7 +71,7 @@ declare abstract class BaseLLM<CallOptions extends BaseLLMCallOptions = BaseLLMC
|
|
|
71
71
|
/**
|
|
72
72
|
* Run the LLM on the given prompts and input, handling caching.
|
|
73
73
|
*/
|
|
74
|
-
generate(prompts: string[], options?: string[] | CallOptions
|
|
74
|
+
generate(prompts: string[], options?: string[] | Partial<CallOptions>, callbacks?: Callbacks): Promise<LLMResult>;
|
|
75
75
|
/**
|
|
76
76
|
* Get the identifying parameters of the LLM.
|
|
77
77
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"llms.d.cts","names":["BasePromptValueInterface","LLMResult","Generation","GenerationChunk","BaseCallbackConfig","CallbackManagerForLLMRun","Callbacks","BaseLanguageModel","BaseLanguageModelCallOptions","BaseLanguageModelInput","BaseLanguageModelParams","RunnableConfig","BaseCache","SerializedLLM","Record","BaseLLMParams","BaseLLMCallOptions","BaseLLM","CallOptions","Exclude","Omit","
|
|
1
|
+
{"version":3,"file":"llms.d.cts","names":["BasePromptValueInterface","LLMResult","Generation","GenerationChunk","BaseCallbackConfig","CallbackManagerForLLMRun","Callbacks","BaseLanguageModel","BaseLanguageModelCallOptions","BaseLanguageModelInput","BaseLanguageModelParams","RunnableConfig","BaseCache","SerializedLLM","Record","BaseLLMParams","BaseLLMCallOptions","BaseLLM","CallOptions","Exclude","Omit","Partial","Promise","AsyncGenerator","prompts","cache","llmStringKey","parsedOptions","handledOptions","runId","LLM"],"sources":["../../src/language_models/llms.d.ts"],"sourcesContent":["import type { BasePromptValueInterface } from \"../prompt_values.js\";\nimport { type LLMResult, type Generation, GenerationChunk } from \"../outputs.js\";\nimport { type BaseCallbackConfig, type CallbackManagerForLLMRun, type Callbacks } from \"../callbacks/manager.js\";\nimport { BaseLanguageModel, type BaseLanguageModelCallOptions, type BaseLanguageModelInput, type BaseLanguageModelParams } from \"./base.js\";\nimport type { RunnableConfig } from \"../runnables/config.js\";\nimport type { BaseCache } from \"../caches/index.js\";\nexport type SerializedLLM = {\n _model: string;\n _type: string;\n} & Record<string, any>;\nexport interface BaseLLMParams extends BaseLanguageModelParams {\n}\nexport interface BaseLLMCallOptions extends BaseLanguageModelCallOptions {\n}\n/**\n * LLM Wrapper. Takes in a prompt (or prompts) and returns a string.\n */\nexport declare abstract class BaseLLM<CallOptions extends BaseLLMCallOptions = BaseLLMCallOptions> extends BaseLanguageModel<string, CallOptions> {\n ParsedCallOptions: Omit<CallOptions, Exclude<keyof RunnableConfig, \"signal\" | \"timeout\" | \"maxConcurrency\">>;\n lc_namespace: string[];\n /**\n * This method takes an input and options, and returns a string. It\n * converts the input to a prompt value and generates a result based on\n * the prompt.\n * @param input Input for the LLM.\n * @param options Options for the LLM call.\n * @returns A string result based on the prompt.\n */\n invoke(input: BaseLanguageModelInput, options?: Partial<CallOptions>): Promise<string>;\n _streamResponseChunks(_input: string, _options: this[\"ParsedCallOptions\"], _runManager?: CallbackManagerForLLMRun): AsyncGenerator<GenerationChunk>;\n protected _separateRunnableConfigFromCallOptionsCompat(options?: Partial<CallOptions>): [RunnableConfig, this[\"ParsedCallOptions\"]];\n _streamIterator(input: BaseLanguageModelInput, options?: Partial<CallOptions>): AsyncGenerator<string>;\n /**\n * This method takes prompt values, options, and callbacks, and generates\n * a result based on the prompts.\n * @param promptValues Prompt values for the LLM.\n * @param options Options for the LLM call.\n * @param callbacks Callbacks for the LLM call.\n * @returns An LLMResult based on the prompts.\n */\n generatePrompt(promptValues: BasePromptValueInterface[], options?: string[] | Partial<CallOptions>, callbacks?: Callbacks): Promise<LLMResult>;\n /**\n * Run the LLM on the given prompts and input.\n */\n abstract _generate(prompts: string[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<LLMResult>;\n /**\n * Get the parameters used to invoke the model\n */\n invocationParams(_options?: this[\"ParsedCallOptions\"]): any;\n _flattenLLMResult(llmResult: LLMResult): LLMResult[];\n /** @ignore */\n _generateUncached(prompts: string[], parsedOptions: this[\"ParsedCallOptions\"], handledOptions: BaseCallbackConfig, startedRunManagers?: CallbackManagerForLLMRun[]): Promise<LLMResult>;\n _generateCached({ prompts, cache, llmStringKey, parsedOptions, handledOptions, runId }: {\n prompts: string[];\n cache: BaseCache<Generation[]>;\n llmStringKey: string;\n parsedOptions: any;\n handledOptions: RunnableConfig;\n runId?: string;\n }): Promise<LLMResult & {\n missingPromptIndices: number[];\n startedRunManagers?: CallbackManagerForLLMRun[];\n }>;\n /**\n * Run the LLM on the given prompts and input, handling caching.\n */\n generate(prompts: string[], options?: string[] | Partial<CallOptions>, callbacks?: Callbacks): Promise<LLMResult>;\n /**\n * Get the identifying parameters of the LLM.\n */\n _identifyingParams(): Record<string, any>;\n /**\n * Return the string type key uniquely identifying this class of LLM.\n */\n abstract _llmType(): string;\n _modelType(): string;\n}\n/**\n * LLM class that provides a simpler interface to subclass than {@link BaseLLM}.\n *\n * Requires only implementing a simpler {@link _call} method instead of {@link _generate}.\n *\n * @augments BaseLLM\n */\nexport declare abstract class LLM<CallOptions extends BaseLLMCallOptions = BaseLLMCallOptions> extends BaseLLM<CallOptions> {\n /**\n * Run the LLM on the given prompt and input.\n */\n abstract _call(prompt: string, options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<string>;\n _generate(prompts: string[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<LLMResult>;\n}\n//# sourceMappingURL=llms.d.ts.map"],"mappings":";;;;;;;;KAMYa,aAAAA;;EAAAA,KAAAA,EAAAA,MAAAA;AAIZ,CAAA,GADIC,MACaC,CAAAA,MAAAA,EAAAA,GAAa,CAAA;AAEbC,UAFAD,aAAAA,SAAsBL,uBAEKF,CAAAA,CAK5C;AAA0DQ,UALzCA,kBAAAA,SAA2BR,4BAKcQ,CAAAA;;;;AACjBG,uBADXF,OACWE,CAAAA,oBADiBH,kBACjBG,GADs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AAA,EAAAA,SAAAA,CAAAA,EAiDpBD,SAjDoBC,CAAAA,EAiDRe,OAjDQf,CAiDAN,SAjDAM,CAAAA;EAAiB;AAmE5H;;EAA2ES,kBAAAA,CAAAA,CAAAA,EAdjDF,MAciDE,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA;EAAoCE;;;EAK7Bb,SAAAA,QAAAA,CAAAA,CAAAA,EAAAA,MAAAA;EAAmCJ,UAAAA,CAAAA,CAAAA,EAAAA,MAAAA;;;AALP;;;;;;uBAAhF6B,wBAAwBd,qBAAqBA,4BAA4BC,QAAQC;;;;kFAI3Bb,2BAA2BiB;gFAC7BjB,2BAA2BiB,QAAQrB"}
|
|
@@ -27,10 +27,10 @@ declare abstract class BaseLLM<CallOptions extends BaseLLMCallOptions = BaseLLMC
|
|
|
27
27
|
* @param options Options for the LLM call.
|
|
28
28
|
* @returns A string result based on the prompt.
|
|
29
29
|
*/
|
|
30
|
-
invoke(input: BaseLanguageModelInput, options?: CallOptions): Promise<string>;
|
|
30
|
+
invoke(input: BaseLanguageModelInput, options?: Partial<CallOptions>): Promise<string>;
|
|
31
31
|
_streamResponseChunks(_input: string, _options: this["ParsedCallOptions"], _runManager?: CallbackManagerForLLMRun): AsyncGenerator<GenerationChunk>;
|
|
32
32
|
protected _separateRunnableConfigFromCallOptionsCompat(options?: Partial<CallOptions>): [RunnableConfig, this["ParsedCallOptions"]];
|
|
33
|
-
_streamIterator(input: BaseLanguageModelInput, options?: CallOptions): AsyncGenerator<string>;
|
|
33
|
+
_streamIterator(input: BaseLanguageModelInput, options?: Partial<CallOptions>): AsyncGenerator<string>;
|
|
34
34
|
/**
|
|
35
35
|
* This method takes prompt values, options, and callbacks, and generates
|
|
36
36
|
* a result based on the prompts.
|
|
@@ -39,7 +39,7 @@ declare abstract class BaseLLM<CallOptions extends BaseLLMCallOptions = BaseLLMC
|
|
|
39
39
|
* @param callbacks Callbacks for the LLM call.
|
|
40
40
|
* @returns An LLMResult based on the prompts.
|
|
41
41
|
*/
|
|
42
|
-
generatePrompt(promptValues: BasePromptValueInterface[], options?: string[] | CallOptions
|
|
42
|
+
generatePrompt(promptValues: BasePromptValueInterface[], options?: string[] | Partial<CallOptions>, callbacks?: Callbacks): Promise<LLMResult>;
|
|
43
43
|
/**
|
|
44
44
|
* Run the LLM on the given prompts and input.
|
|
45
45
|
*/
|
|
@@ -72,7 +72,7 @@ declare abstract class BaseLLM<CallOptions extends BaseLLMCallOptions = BaseLLMC
|
|
|
72
72
|
/**
|
|
73
73
|
* Run the LLM on the given prompts and input, handling caching.
|
|
74
74
|
*/
|
|
75
|
-
generate(prompts: string[], options?: string[] | CallOptions
|
|
75
|
+
generate(prompts: string[], options?: string[] | Partial<CallOptions>, callbacks?: Callbacks): Promise<LLMResult>;
|
|
76
76
|
/**
|
|
77
77
|
* Get the identifying parameters of the LLM.
|
|
78
78
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"llms.d.ts","names":["BasePromptValueInterface","LLMResult","Generation","GenerationChunk","BaseCallbackConfig","CallbackManagerForLLMRun","Callbacks","BaseLanguageModel","BaseLanguageModelCallOptions","BaseLanguageModelInput","BaseLanguageModelParams","RunnableConfig","BaseCache","SerializedLLM","Record","BaseLLMParams","BaseLLMCallOptions","BaseLLM","CallOptions","Exclude","Omit","
|
|
1
|
+
{"version":3,"file":"llms.d.ts","names":["BasePromptValueInterface","LLMResult","Generation","GenerationChunk","BaseCallbackConfig","CallbackManagerForLLMRun","Callbacks","BaseLanguageModel","BaseLanguageModelCallOptions","BaseLanguageModelInput","BaseLanguageModelParams","RunnableConfig","BaseCache","SerializedLLM","Record","BaseLLMParams","BaseLLMCallOptions","BaseLLM","CallOptions","Exclude","Omit","Partial","Promise","AsyncGenerator","prompts","cache","llmStringKey","parsedOptions","handledOptions","runId","LLM"],"sources":["../../src/language_models/llms.d.ts"],"sourcesContent":["import type { BasePromptValueInterface } from \"../prompt_values.js\";\nimport { type LLMResult, type Generation, GenerationChunk } from \"../outputs.js\";\nimport { type BaseCallbackConfig, type CallbackManagerForLLMRun, type Callbacks } from \"../callbacks/manager.js\";\nimport { BaseLanguageModel, type BaseLanguageModelCallOptions, type BaseLanguageModelInput, type BaseLanguageModelParams } from \"./base.js\";\nimport type { RunnableConfig } from \"../runnables/config.js\";\nimport type { BaseCache } from \"../caches/index.js\";\nexport type SerializedLLM = {\n _model: string;\n _type: string;\n} & Record<string, any>;\nexport interface BaseLLMParams extends BaseLanguageModelParams {\n}\nexport interface BaseLLMCallOptions extends BaseLanguageModelCallOptions {\n}\n/**\n * LLM Wrapper. Takes in a prompt (or prompts) and returns a string.\n */\nexport declare abstract class BaseLLM<CallOptions extends BaseLLMCallOptions = BaseLLMCallOptions> extends BaseLanguageModel<string, CallOptions> {\n ParsedCallOptions: Omit<CallOptions, Exclude<keyof RunnableConfig, \"signal\" | \"timeout\" | \"maxConcurrency\">>;\n lc_namespace: string[];\n /**\n * This method takes an input and options, and returns a string. It\n * converts the input to a prompt value and generates a result based on\n * the prompt.\n * @param input Input for the LLM.\n * @param options Options for the LLM call.\n * @returns A string result based on the prompt.\n */\n invoke(input: BaseLanguageModelInput, options?: Partial<CallOptions>): Promise<string>;\n _streamResponseChunks(_input: string, _options: this[\"ParsedCallOptions\"], _runManager?: CallbackManagerForLLMRun): AsyncGenerator<GenerationChunk>;\n protected _separateRunnableConfigFromCallOptionsCompat(options?: Partial<CallOptions>): [RunnableConfig, this[\"ParsedCallOptions\"]];\n _streamIterator(input: BaseLanguageModelInput, options?: Partial<CallOptions>): AsyncGenerator<string>;\n /**\n * This method takes prompt values, options, and callbacks, and generates\n * a result based on the prompts.\n * @param promptValues Prompt values for the LLM.\n * @param options Options for the LLM call.\n * @param callbacks Callbacks for the LLM call.\n * @returns An LLMResult based on the prompts.\n */\n generatePrompt(promptValues: BasePromptValueInterface[], options?: string[] | Partial<CallOptions>, callbacks?: Callbacks): Promise<LLMResult>;\n /**\n * Run the LLM on the given prompts and input.\n */\n abstract _generate(prompts: string[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<LLMResult>;\n /**\n * Get the parameters used to invoke the model\n */\n invocationParams(_options?: this[\"ParsedCallOptions\"]): any;\n _flattenLLMResult(llmResult: LLMResult): LLMResult[];\n /** @ignore */\n _generateUncached(prompts: string[], parsedOptions: this[\"ParsedCallOptions\"], handledOptions: BaseCallbackConfig, startedRunManagers?: CallbackManagerForLLMRun[]): Promise<LLMResult>;\n _generateCached({ prompts, cache, llmStringKey, parsedOptions, handledOptions, runId }: {\n prompts: string[];\n cache: BaseCache<Generation[]>;\n llmStringKey: string;\n parsedOptions: any;\n handledOptions: RunnableConfig;\n runId?: string;\n }): Promise<LLMResult & {\n missingPromptIndices: number[];\n startedRunManagers?: CallbackManagerForLLMRun[];\n }>;\n /**\n * Run the LLM on the given prompts and input, handling caching.\n */\n generate(prompts: string[], options?: string[] | Partial<CallOptions>, callbacks?: Callbacks): Promise<LLMResult>;\n /**\n * Get the identifying parameters of the LLM.\n */\n _identifyingParams(): Record<string, any>;\n /**\n * Return the string type key uniquely identifying this class of LLM.\n */\n abstract _llmType(): string;\n _modelType(): string;\n}\n/**\n * LLM class that provides a simpler interface to subclass than {@link BaseLLM}.\n *\n * Requires only implementing a simpler {@link _call} method instead of {@link _generate}.\n *\n * @augments BaseLLM\n */\nexport declare abstract class LLM<CallOptions extends BaseLLMCallOptions = BaseLLMCallOptions> extends BaseLLM<CallOptions> {\n /**\n * Run the LLM on the given prompt and input.\n */\n abstract _call(prompt: string, options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<string>;\n _generate(prompts: string[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<LLMResult>;\n}\n//# sourceMappingURL=llms.d.ts.map"],"mappings":";;;;;;;;;KAMYa,aAAAA;;;AAAZ,CAAA,GAGIC,MAHQD,CAAAA,MAAAA,EAAAA,GAAa,CAAA;AAIRE,UAAAA,aAAAA,SAAsBL,uBAAuB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A,CAAAA,OAAAA,EAAAA,MAAAA,EAAAA,EAAAA,OAAAA,CAAAA,EAAAA,MAAAA,EAAAA,GAJ2BO,OAI3BP,CAJmCI,WAInCJ,CAAAA,EAAAA,SAAAA,CAAAA,EAJ6DR,SAI7DQ,CAAAA,EAJyEQ,OAIzER,CAJiFb,SAIjFa,CAAAA;EArDiFP;AAAiB;AAmE5H;EAAsDS,kBAAAA,CAAAA,CAAAA,EAd5BF,MAc4BE,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA;EAAqBA;;;EAIoCM,SAAAA,QAAAA,CAAAA,CAAAA,EAAAA,MAAAA;EAC7BjB,UAAAA,CAAAA,CAAAA,EAAAA,MAAAA;;;;AAL4B;;;;;uBAAhFyB,wBAAwBd,qBAAqBA,4BAA4BC,QAAQC;;;;kFAI3Bb,2BAA2BiB;gFAC7BjB,2BAA2BiB,QAAQrB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"llms.js","names":["input: BaseLanguageModelInput","options?: CallOptions","_input: string","_options: this[\"ParsedCallOptions\"]","_runManager?: CallbackManagerForLLMRun","options?: Partial<CallOptions>","promptValues: BasePromptValueInterface[]","options?: string[] | CallOptions","callbacks?: Callbacks","prompts: string[]","_options?: this[\"ParsedCallOptions\"]","llmResult: LLMResult","llmResults: LLMResult[]","parsedOptions: this[\"ParsedCallOptions\"]","handledOptions: BaseCallbackConfig","startedRunManagers?: CallbackManagerForLLMRun[]","runManagers: CallbackManagerForLLMRun[] | undefined","output: LLMResult","flattenedOutputs: LLMResult[]","missingPromptIndices: number[]","generations: Generation[][]","result","parsedOptions: CallOptions | undefined","options: this[\"ParsedCallOptions\"]","runManager?: CallbackManagerForLLMRun"],"sources":["../../src/language_models/llms.ts"],"sourcesContent":["import type { BasePromptValueInterface } from \"../prompt_values.js\";\nimport {\n type LLMResult,\n RUN_KEY,\n type Generation,\n GenerationChunk,\n} from \"../outputs.js\";\nimport {\n type BaseCallbackConfig,\n CallbackManager,\n type CallbackManagerForLLMRun,\n type Callbacks,\n} from \"../callbacks/manager.js\";\nimport {\n BaseLanguageModel,\n type BaseLanguageModelCallOptions,\n type BaseLanguageModelInput,\n type BaseLanguageModelParams,\n} from \"./base.js\";\nimport type { RunnableConfig } from \"../runnables/config.js\";\nimport type { BaseCache } from \"../caches/index.js\";\nimport { concat } from \"../utils/stream.js\";\nimport { callbackHandlerPrefersStreaming } from \"../callbacks/base.js\";\n\nexport type SerializedLLM = {\n _model: string;\n _type: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n} & Record<string, any>;\n\nexport interface BaseLLMParams extends BaseLanguageModelParams {}\n\nexport interface BaseLLMCallOptions extends BaseLanguageModelCallOptions {}\n\n/**\n * LLM Wrapper. Takes in a prompt (or prompts) and returns a string.\n */\nexport abstract class BaseLLM<\n CallOptions extends BaseLLMCallOptions = BaseLLMCallOptions,\n> extends BaseLanguageModel<string, CallOptions> {\n // Backwards compatibility since fields have been moved to RunnableConfig\n declare ParsedCallOptions: Omit<\n CallOptions,\n Exclude<keyof RunnableConfig, \"signal\" | \"timeout\" | \"maxConcurrency\">\n >;\n\n // Only ever instantiated in main LangChain\n lc_namespace = [\"langchain\", \"llms\", this._llmType()];\n\n /**\n * This method takes an input and options, and returns a string. It\n * converts the input to a prompt value and generates a result based on\n * the prompt.\n * @param input Input for the LLM.\n * @param options Options for the LLM call.\n * @returns A string result based on the prompt.\n */\n async invoke(\n input: BaseLanguageModelInput,\n options?: CallOptions\n ): Promise<string> {\n const promptValue = BaseLLM._convertInputToPromptValue(input);\n const result = await this.generatePrompt(\n [promptValue],\n options,\n options?.callbacks\n );\n return result.generations[0][0].text;\n }\n\n // eslint-disable-next-line require-yield\n async *_streamResponseChunks(\n _input: string,\n _options: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<GenerationChunk> {\n throw new Error(\"Not implemented.\");\n }\n\n protected _separateRunnableConfigFromCallOptionsCompat(\n options?: Partial<CallOptions>\n ): [RunnableConfig, this[\"ParsedCallOptions\"]] {\n // For backwards compat, keep `signal` in both runnableConfig and callOptions\n const [runnableConfig, callOptions] =\n super._separateRunnableConfigFromCallOptions(options);\n (callOptions as this[\"ParsedCallOptions\"]).signal = runnableConfig.signal;\n return [runnableConfig, callOptions as this[\"ParsedCallOptions\"]];\n }\n\n async *_streamIterator(\n input: BaseLanguageModelInput,\n options?: CallOptions\n ): AsyncGenerator<string> {\n // Subclass check required to avoid double callbacks with default implementation\n if (\n this._streamResponseChunks === BaseLLM.prototype._streamResponseChunks\n ) {\n yield this.invoke(input, options);\n } else {\n const prompt = BaseLLM._convertInputToPromptValue(input);\n const [runnableConfig, callOptions] =\n this._separateRunnableConfigFromCallOptionsCompat(options);\n const callbackManager_ = await CallbackManager.configure(\n runnableConfig.callbacks,\n this.callbacks,\n runnableConfig.tags,\n this.tags,\n runnableConfig.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const extra = {\n options: callOptions,\n invocation_params: this?.invocationParams(callOptions),\n batch_size: 1,\n };\n const runManagers = await callbackManager_?.handleLLMStart(\n this.toJSON(),\n [prompt.toString()],\n runnableConfig.runId,\n undefined,\n extra,\n undefined,\n undefined,\n runnableConfig.runName\n );\n let generation = new GenerationChunk({\n text: \"\",\n });\n try {\n for await (const chunk of this._streamResponseChunks(\n prompt.toString(),\n callOptions,\n runManagers?.[0]\n )) {\n if (!generation) {\n generation = chunk;\n } else {\n generation = generation.concat(chunk);\n }\n if (typeof chunk.text === \"string\") {\n yield chunk.text;\n }\n }\n } catch (err) {\n await Promise.all(\n (runManagers ?? []).map((runManager) =>\n runManager?.handleLLMError(err)\n )\n );\n throw err;\n }\n await Promise.all(\n (runManagers ?? []).map((runManager) =>\n runManager?.handleLLMEnd({\n generations: [[generation]],\n })\n )\n );\n }\n }\n\n /**\n * This method takes prompt values, options, and callbacks, and generates\n * a result based on the prompts.\n * @param promptValues Prompt values for the LLM.\n * @param options Options for the LLM call.\n * @param callbacks Callbacks for the LLM call.\n * @returns An LLMResult based on the prompts.\n */\n async generatePrompt(\n promptValues: BasePromptValueInterface[],\n options?: string[] | CallOptions,\n callbacks?: Callbacks\n ): Promise<LLMResult> {\n const prompts: string[] = promptValues.map((promptValue) =>\n promptValue.toString()\n );\n return this.generate(prompts, options, callbacks);\n }\n\n /**\n * Run the LLM on the given prompts and input.\n */\n abstract _generate(\n prompts: string[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<LLMResult>;\n\n /**\n * Get the parameters used to invoke the model\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invocationParams(_options?: this[\"ParsedCallOptions\"]): any {\n return {};\n }\n\n _flattenLLMResult(llmResult: LLMResult): LLMResult[] {\n const llmResults: LLMResult[] = [];\n\n for (let i = 0; i < llmResult.generations.length; i += 1) {\n const genList = llmResult.generations[i];\n\n if (i === 0) {\n llmResults.push({\n generations: [genList],\n llmOutput: llmResult.llmOutput,\n });\n } else {\n const llmOutput = llmResult.llmOutput\n ? { ...llmResult.llmOutput, tokenUsage: {} }\n : undefined;\n\n llmResults.push({\n generations: [genList],\n llmOutput,\n });\n }\n }\n\n return llmResults;\n }\n\n /** @ignore */\n async _generateUncached(\n prompts: string[],\n parsedOptions: this[\"ParsedCallOptions\"],\n handledOptions: BaseCallbackConfig,\n startedRunManagers?: CallbackManagerForLLMRun[]\n ): Promise<LLMResult> {\n let runManagers: CallbackManagerForLLMRun[] | undefined;\n if (\n startedRunManagers !== undefined &&\n startedRunManagers.length === prompts.length\n ) {\n runManagers = startedRunManagers;\n } else {\n const callbackManager_ = await CallbackManager.configure(\n handledOptions.callbacks,\n this.callbacks,\n handledOptions.tags,\n this.tags,\n handledOptions.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const extra = {\n options: parsedOptions,\n invocation_params: this?.invocationParams(parsedOptions),\n batch_size: prompts.length,\n };\n runManagers = await callbackManager_?.handleLLMStart(\n this.toJSON(),\n prompts,\n handledOptions.runId,\n undefined,\n extra,\n undefined,\n undefined,\n handledOptions?.runName\n );\n }\n // Even if stream is not explicitly called, check if model is implicitly\n // called from streamEvents() or streamLog() to get all streamed events.\n // Bail out if _streamResponseChunks not overridden\n const hasStreamingHandler = !!runManagers?.[0].handlers.find(\n callbackHandlerPrefersStreaming\n );\n let output: LLMResult;\n if (\n hasStreamingHandler &&\n prompts.length === 1 &&\n this._streamResponseChunks !== BaseLLM.prototype._streamResponseChunks\n ) {\n try {\n const stream = await this._streamResponseChunks(\n prompts[0],\n parsedOptions,\n runManagers?.[0]\n );\n let aggregated;\n for await (const chunk of stream) {\n if (aggregated === undefined) {\n aggregated = chunk;\n } else {\n aggregated = concat(aggregated, chunk);\n }\n }\n if (aggregated === undefined) {\n throw new Error(\"Received empty response from chat model call.\");\n }\n output = { generations: [[aggregated]], llmOutput: {} };\n await runManagers?.[0].handleLLMEnd(output);\n } catch (e) {\n await runManagers?.[0].handleLLMError(e);\n throw e;\n }\n } else {\n try {\n output = await this._generate(prompts, parsedOptions, runManagers?.[0]);\n } catch (err) {\n await Promise.all(\n (runManagers ?? []).map((runManager) =>\n runManager?.handleLLMError(err)\n )\n );\n throw err;\n }\n\n const flattenedOutputs: LLMResult[] = this._flattenLLMResult(output);\n await Promise.all(\n (runManagers ?? []).map((runManager, i) =>\n runManager?.handleLLMEnd(flattenedOutputs[i])\n )\n );\n }\n const runIds = runManagers?.map((manager) => manager.runId) || undefined;\n // This defines RUN_KEY as a non-enumerable property on the output object\n // so that it is not serialized when the output is stringified, and so that\n // it isnt included when listing the keys of the output object.\n Object.defineProperty(output, RUN_KEY, {\n value: runIds ? { runIds } : undefined,\n configurable: true,\n });\n return output;\n }\n\n async _generateCached({\n prompts,\n cache,\n llmStringKey,\n parsedOptions,\n handledOptions,\n runId,\n }: {\n prompts: string[];\n cache: BaseCache<Generation[]>;\n llmStringKey: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parsedOptions: any;\n handledOptions: RunnableConfig;\n runId?: string;\n }): Promise<\n LLMResult & {\n missingPromptIndices: number[];\n startedRunManagers?: CallbackManagerForLLMRun[];\n }\n > {\n const callbackManager_ = await CallbackManager.configure(\n handledOptions.callbacks,\n this.callbacks,\n handledOptions.tags,\n this.tags,\n handledOptions.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const extra = {\n options: parsedOptions,\n invocation_params: this?.invocationParams(parsedOptions),\n batch_size: prompts.length,\n };\n const runManagers = await callbackManager_?.handleLLMStart(\n this.toJSON(),\n prompts,\n runId,\n undefined,\n extra,\n undefined,\n undefined,\n handledOptions?.runName\n );\n\n // generate results\n const missingPromptIndices: number[] = [];\n const results = await Promise.allSettled(\n prompts.map(async (prompt, index) => {\n const result = await cache.lookup(prompt, llmStringKey);\n if (result == null) {\n missingPromptIndices.push(index);\n }\n return result;\n })\n );\n\n // Map run managers to the results before filtering out null results\n // Null results are just absent from the cache.\n const cachedResults = results\n .map((result, index) => ({ result, runManager: runManagers?.[index] }))\n .filter(\n ({ result }) =>\n (result.status === \"fulfilled\" && result.value != null) ||\n result.status === \"rejected\"\n );\n\n // Handle results and call run managers\n const generations: Generation[][] = [];\n await Promise.all(\n cachedResults.map(async ({ result: promiseResult, runManager }, i) => {\n if (promiseResult.status === \"fulfilled\") {\n const result = promiseResult.value as Generation[];\n generations[i] = result.map((result) => {\n result.generationInfo = {\n ...result.generationInfo,\n tokenUsage: {},\n };\n return result;\n });\n if (result.length) {\n await runManager?.handleLLMNewToken(result[0].text);\n }\n return runManager?.handleLLMEnd(\n {\n generations: [result],\n },\n undefined,\n undefined,\n undefined,\n {\n cached: true,\n }\n );\n } else {\n // status === \"rejected\"\n await runManager?.handleLLMError(\n promiseResult.reason,\n undefined,\n undefined,\n undefined,\n {\n cached: true,\n }\n );\n return Promise.reject(promiseResult.reason);\n }\n })\n );\n\n const output = {\n generations,\n missingPromptIndices,\n startedRunManagers: runManagers,\n };\n\n // This defines RUN_KEY as a non-enumerable property on the output object\n // so that it is not serialized when the output is stringified, and so that\n // it isnt included when listing the keys of the output object.\n Object.defineProperty(output, RUN_KEY, {\n value: runManagers\n ? { runIds: runManagers?.map((manager) => manager.runId) }\n : undefined,\n configurable: true,\n });\n\n return output;\n }\n\n /**\n * Run the LLM on the given prompts and input, handling caching.\n */\n async generate(\n prompts: string[],\n options?: string[] | CallOptions,\n callbacks?: Callbacks\n ): Promise<LLMResult> {\n if (!Array.isArray(prompts)) {\n throw new Error(\"Argument 'prompts' is expected to be a string[]\");\n }\n\n let parsedOptions: CallOptions | undefined;\n if (Array.isArray(options)) {\n parsedOptions = { stop: options } as CallOptions;\n } else {\n parsedOptions = options;\n }\n\n const [runnableConfig, callOptions] =\n this._separateRunnableConfigFromCallOptionsCompat(parsedOptions);\n runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks;\n\n if (!this.cache) {\n return this._generateUncached(prompts, callOptions, runnableConfig);\n }\n\n const { cache } = this;\n const llmStringKey = this._getSerializedCacheKeyParametersForCall(\n callOptions as CallOptions\n );\n const { generations, missingPromptIndices, startedRunManagers } =\n await this._generateCached({\n prompts,\n cache,\n llmStringKey,\n parsedOptions: callOptions,\n handledOptions: runnableConfig,\n runId: runnableConfig.runId,\n });\n\n let llmOutput = {};\n if (missingPromptIndices.length > 0) {\n const results = await this._generateUncached(\n missingPromptIndices.map((i) => prompts[i]),\n callOptions,\n runnableConfig,\n startedRunManagers !== undefined\n ? missingPromptIndices.map((i) => startedRunManagers?.[i])\n : undefined\n );\n await Promise.all(\n results.generations.map(async (generation, index) => {\n const promptIndex = missingPromptIndices[index];\n generations[promptIndex] = generation;\n return cache.update(prompts[promptIndex], llmStringKey, generation);\n })\n );\n llmOutput = results.llmOutput ?? {};\n }\n\n return { generations, llmOutput } as LLMResult;\n }\n\n /**\n * Get the identifying parameters of the LLM.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _identifyingParams(): Record<string, any> {\n return {};\n }\n\n /**\n * Return the string type key uniquely identifying this class of LLM.\n */\n abstract _llmType(): string;\n\n _modelType(): string {\n return \"base_llm\" as const;\n }\n}\n\n/**\n * LLM class that provides a simpler interface to subclass than {@link BaseLLM}.\n *\n * Requires only implementing a simpler {@link _call} method instead of {@link _generate}.\n *\n * @augments BaseLLM\n */\nexport abstract class LLM<\n CallOptions extends BaseLLMCallOptions = BaseLLMCallOptions,\n> extends BaseLLM<CallOptions> {\n /**\n * Run the LLM on the given prompt and input.\n */\n abstract _call(\n prompt: string,\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<string>;\n\n async _generate(\n prompts: string[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<LLMResult> {\n const generations: Generation[][] = await Promise.all(\n prompts.map((prompt, promptIndex) =>\n this._call(prompt, { ...options, promptIndex }, runManager).then(\n (text) => [{ text }]\n )\n )\n );\n return { generations };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqCA,IAAsB,UAAtB,MAAsB,gBAEZ,kBAAuC;CAQ/C,eAAe;EAAC;EAAa;EAAQ,KAAK,UAAU;CAAC;;;;;;;;;CAUrD,MAAM,OACJA,OACAC,SACiB;EACjB,MAAM,cAAc,QAAQ,2BAA2B,MAAM;EAC7D,MAAM,SAAS,MAAM,KAAK,eACxB,CAAC,WAAY,GACb,SACA,SAAS,UACV;AACD,SAAO,OAAO,YAAY,GAAG,GAAG;CACjC;CAGD,OAAO,sBACLC,QACAC,UACAC,aACiC;AACjC,QAAM,IAAI,MAAM;CACjB;CAED,AAAU,6CACRC,SAC6C;EAE7C,MAAM,CAAC,gBAAgB,YAAY,GACjC,MAAM,uCAAuC,QAAQ;EACtD,YAA0C,SAAS,eAAe;AACnE,SAAO,CAAC,gBAAgB,WAAyC;CAClE;CAED,OAAO,gBACLL,OACAC,SACwB;AAExB,MACE,KAAK,0BAA0B,QAAQ,UAAU,uBAEjD,MAAM,KAAK,OAAO,OAAO,QAAQ;OAC5B;GACL,MAAM,SAAS,QAAQ,2BAA2B,MAAM;GACxD,MAA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B,SAAS,aAAa,eAAe;EAGrE,MAAM,EAAE,OAAO,GAAG;EAClB,MAAM,eAAe,KAAK,wCACxB,YACD;EACD,MAAM,EAAE,aAAa,sBAAsB,oBAAoB,GAC7D,MAAM,KAAK,gBAAgB;GACzB;GACA;GACA;GACA,eAAe;GACf,gBAAgB;GAChB,OAAO,eAAe;EACvB,EAAC;EAEJ,IAAI,YAAY,CAAE;AAClB,MAAI,qBAAqB,SAAS,GAAG;GACnC,MAAM,UAAU,MAAM,KAAK,kBACzB,qBAAqB,IAAI,CAAC,MAAM,QAAQ,GAAG,EAC3C,aACA,gBACA,uBAAuB,SACnB,qBAAqB,IAAI,CAAC,MAAM,qBAAqB,GAAG,GACxD,OACL;GACD,MAAM,QAAQ,IACZ,QAAQ,YAAY,IAAI,OAAO,YAAY,UAAU;IACnD,MAAM,cAAc,qBAAqB;IACzC,YAAY,eAAe;AAC3B,WAAO,MAAM,OAAO,QAAQ,cAAc,cAAc,WAAW;GACpE,EAAC,CACH;GACD,YAAY,QAAQ,aAAa,CAAE;EACpC;AAED,SAAO;GAAE;GAAa;EAAW;CAClC;;;;CAMD,qBAA0C;AACxC,SAAO,CAAE;CACV;CAOD,aAAqB;AACnB,SAAO;CACR;AACF;;;;;;;;AASD,IAAsB,MAAtB,cAEU,QAAqB;CAU7B,MAAM,UACJb,SACAc,SACAC,YACoB;EACpB,MAAMJ,cAA8B,MAAM,QAAQ,IAChD,QAAQ,IAAI,CAAC,QAAQ,gBACnB,KAAK,MAAM,QAAQ;GAAE,GAAG;GAAS;EAAa,GAAE,WAAW,CAAC,KAC1D,CAAC,SAAS,CAAC,EAAE,KAAM,CAAC,EACrB,CACF,CACF;AACD,SAAO,EAAE,YAAa;CACvB;AACF"}
|
|
1
|
+
{"version":3,"file":"llms.js","names":["input: BaseLanguageModelInput","options?: Partial<CallOptions>","_input: string","_options: this[\"ParsedCallOptions\"]","_runManager?: CallbackManagerForLLMRun","promptValues: BasePromptValueInterface[]","options?: string[] | Partial<CallOptions>","callbacks?: Callbacks","prompts: string[]","_options?: this[\"ParsedCallOptions\"]","llmResult: LLMResult","llmResults: LLMResult[]","parsedOptions: this[\"ParsedCallOptions\"]","handledOptions: BaseCallbackConfig","startedRunManagers?: CallbackManagerForLLMRun[]","runManagers: CallbackManagerForLLMRun[] | undefined","output: LLMResult","flattenedOutputs: LLMResult[]","missingPromptIndices: number[]","generations: Generation[][]","result","parsedOptions: Partial<CallOptions> | undefined","options: this[\"ParsedCallOptions\"]","runManager?: CallbackManagerForLLMRun"],"sources":["../../src/language_models/llms.ts"],"sourcesContent":["import type { BasePromptValueInterface } from \"../prompt_values.js\";\nimport {\n type LLMResult,\n RUN_KEY,\n type Generation,\n GenerationChunk,\n} from \"../outputs.js\";\nimport {\n type BaseCallbackConfig,\n CallbackManager,\n type CallbackManagerForLLMRun,\n type Callbacks,\n} from \"../callbacks/manager.js\";\nimport {\n BaseLanguageModel,\n type BaseLanguageModelCallOptions,\n type BaseLanguageModelInput,\n type BaseLanguageModelParams,\n} from \"./base.js\";\nimport type { RunnableConfig } from \"../runnables/config.js\";\nimport type { BaseCache } from \"../caches/index.js\";\nimport { concat } from \"../utils/stream.js\";\nimport { callbackHandlerPrefersStreaming } from \"../callbacks/base.js\";\n\nexport type SerializedLLM = {\n _model: string;\n _type: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n} & Record<string, any>;\n\nexport interface BaseLLMParams extends BaseLanguageModelParams {}\n\nexport interface BaseLLMCallOptions extends BaseLanguageModelCallOptions {}\n\n/**\n * LLM Wrapper. Takes in a prompt (or prompts) and returns a string.\n */\nexport abstract class BaseLLM<\n CallOptions extends BaseLLMCallOptions = BaseLLMCallOptions,\n> extends BaseLanguageModel<string, CallOptions> {\n // Backwards compatibility since fields have been moved to RunnableConfig\n declare ParsedCallOptions: Omit<\n CallOptions,\n Exclude<keyof RunnableConfig, \"signal\" | \"timeout\" | \"maxConcurrency\">\n >;\n\n // Only ever instantiated in main LangChain\n lc_namespace = [\"langchain\", \"llms\", this._llmType()];\n\n /**\n * This method takes an input and options, and returns a string. It\n * converts the input to a prompt value and generates a result based on\n * the prompt.\n * @param input Input for the LLM.\n * @param options Options for the LLM call.\n * @returns A string result based on the prompt.\n */\n async invoke(\n input: BaseLanguageModelInput,\n options?: Partial<CallOptions>\n ): Promise<string> {\n const promptValue = BaseLLM._convertInputToPromptValue(input);\n const result = await this.generatePrompt(\n [promptValue],\n options,\n options?.callbacks\n );\n return result.generations[0][0].text;\n }\n\n // eslint-disable-next-line require-yield\n async *_streamResponseChunks(\n _input: string,\n _options: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<GenerationChunk> {\n throw new Error(\"Not implemented.\");\n }\n\n protected _separateRunnableConfigFromCallOptionsCompat(\n options?: Partial<CallOptions>\n ): [RunnableConfig, this[\"ParsedCallOptions\"]] {\n // For backwards compat, keep `signal` in both runnableConfig and callOptions\n const [runnableConfig, callOptions] =\n super._separateRunnableConfigFromCallOptions(options);\n (callOptions as this[\"ParsedCallOptions\"]).signal = runnableConfig.signal;\n return [runnableConfig, callOptions as this[\"ParsedCallOptions\"]];\n }\n\n async *_streamIterator(\n input: BaseLanguageModelInput,\n options?: Partial<CallOptions>\n ): AsyncGenerator<string> {\n // Subclass check required to avoid double callbacks with default implementation\n if (\n this._streamResponseChunks === BaseLLM.prototype._streamResponseChunks\n ) {\n yield this.invoke(input, options);\n } else {\n const prompt = BaseLLM._convertInputToPromptValue(input);\n const [runnableConfig, callOptions] =\n this._separateRunnableConfigFromCallOptionsCompat(options);\n const callbackManager_ = await CallbackManager.configure(\n runnableConfig.callbacks,\n this.callbacks,\n runnableConfig.tags,\n this.tags,\n runnableConfig.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const extra = {\n options: callOptions,\n invocation_params: this?.invocationParams(callOptions),\n batch_size: 1,\n };\n const runManagers = await callbackManager_?.handleLLMStart(\n this.toJSON(),\n [prompt.toString()],\n runnableConfig.runId,\n undefined,\n extra,\n undefined,\n undefined,\n runnableConfig.runName\n );\n let generation = new GenerationChunk({\n text: \"\",\n });\n try {\n for await (const chunk of this._streamResponseChunks(\n prompt.toString(),\n callOptions,\n runManagers?.[0]\n )) {\n if (!generation) {\n generation = chunk;\n } else {\n generation = generation.concat(chunk);\n }\n if (typeof chunk.text === \"string\") {\n yield chunk.text;\n }\n }\n } catch (err) {\n await Promise.all(\n (runManagers ?? []).map((runManager) =>\n runManager?.handleLLMError(err)\n )\n );\n throw err;\n }\n await Promise.all(\n (runManagers ?? []).map((runManager) =>\n runManager?.handleLLMEnd({\n generations: [[generation]],\n })\n )\n );\n }\n }\n\n /**\n * This method takes prompt values, options, and callbacks, and generates\n * a result based on the prompts.\n * @param promptValues Prompt values for the LLM.\n * @param options Options for the LLM call.\n * @param callbacks Callbacks for the LLM call.\n * @returns An LLMResult based on the prompts.\n */\n async generatePrompt(\n promptValues: BasePromptValueInterface[],\n options?: string[] | Partial<CallOptions>,\n callbacks?: Callbacks\n ): Promise<LLMResult> {\n const prompts: string[] = promptValues.map((promptValue) =>\n promptValue.toString()\n );\n return this.generate(prompts, options, callbacks);\n }\n\n /**\n * Run the LLM on the given prompts and input.\n */\n abstract _generate(\n prompts: string[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<LLMResult>;\n\n /**\n * Get the parameters used to invoke the model\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invocationParams(_options?: this[\"ParsedCallOptions\"]): any {\n return {};\n }\n\n _flattenLLMResult(llmResult: LLMResult): LLMResult[] {\n const llmResults: LLMResult[] = [];\n\n for (let i = 0; i < llmResult.generations.length; i += 1) {\n const genList = llmResult.generations[i];\n\n if (i === 0) {\n llmResults.push({\n generations: [genList],\n llmOutput: llmResult.llmOutput,\n });\n } else {\n const llmOutput = llmResult.llmOutput\n ? { ...llmResult.llmOutput, tokenUsage: {} }\n : undefined;\n\n llmResults.push({\n generations: [genList],\n llmOutput,\n });\n }\n }\n\n return llmResults;\n }\n\n /** @ignore */\n async _generateUncached(\n prompts: string[],\n parsedOptions: this[\"ParsedCallOptions\"],\n handledOptions: BaseCallbackConfig,\n startedRunManagers?: CallbackManagerForLLMRun[]\n ): Promise<LLMResult> {\n let runManagers: CallbackManagerForLLMRun[] | undefined;\n if (\n startedRunManagers !== undefined &&\n startedRunManagers.length === prompts.length\n ) {\n runManagers = startedRunManagers;\n } else {\n const callbackManager_ = await CallbackManager.configure(\n handledOptions.callbacks,\n this.callbacks,\n handledOptions.tags,\n this.tags,\n handledOptions.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const extra = {\n options: parsedOptions,\n invocation_params: this?.invocationParams(parsedOptions),\n batch_size: prompts.length,\n };\n runManagers = await callbackManager_?.handleLLMStart(\n this.toJSON(),\n prompts,\n handledOptions.runId,\n undefined,\n extra,\n undefined,\n undefined,\n handledOptions?.runName\n );\n }\n // Even if stream is not explicitly called, check if model is implicitly\n // called from streamEvents() or streamLog() to get all streamed events.\n // Bail out if _streamResponseChunks not overridden\n const hasStreamingHandler = !!runManagers?.[0].handlers.find(\n callbackHandlerPrefersStreaming\n );\n let output: LLMResult;\n if (\n hasStreamingHandler &&\n prompts.length === 1 &&\n this._streamResponseChunks !== BaseLLM.prototype._streamResponseChunks\n ) {\n try {\n const stream = await this._streamResponseChunks(\n prompts[0],\n parsedOptions,\n runManagers?.[0]\n );\n let aggregated;\n for await (const chunk of stream) {\n if (aggregated === undefined) {\n aggregated = chunk;\n } else {\n aggregated = concat(aggregated, chunk);\n }\n }\n if (aggregated === undefined) {\n throw new Error(\"Received empty response from chat model call.\");\n }\n output = { generations: [[aggregated]], llmOutput: {} };\n await runManagers?.[0].handleLLMEnd(output);\n } catch (e) {\n await runManagers?.[0].handleLLMError(e);\n throw e;\n }\n } else {\n try {\n output = await this._generate(prompts, parsedOptions, runManagers?.[0]);\n } catch (err) {\n await Promise.all(\n (runManagers ?? []).map((runManager) =>\n runManager?.handleLLMError(err)\n )\n );\n throw err;\n }\n\n const flattenedOutputs: LLMResult[] = this._flattenLLMResult(output);\n await Promise.all(\n (runManagers ?? []).map((runManager, i) =>\n runManager?.handleLLMEnd(flattenedOutputs[i])\n )\n );\n }\n const runIds = runManagers?.map((manager) => manager.runId) || undefined;\n // This defines RUN_KEY as a non-enumerable property on the output object\n // so that it is not serialized when the output is stringified, and so that\n // it isnt included when listing the keys of the output object.\n Object.defineProperty(output, RUN_KEY, {\n value: runIds ? { runIds } : undefined,\n configurable: true,\n });\n return output;\n }\n\n async _generateCached({\n prompts,\n cache,\n llmStringKey,\n parsedOptions,\n handledOptions,\n runId,\n }: {\n prompts: string[];\n cache: BaseCache<Generation[]>;\n llmStringKey: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parsedOptions: any;\n handledOptions: RunnableConfig;\n runId?: string;\n }): Promise<\n LLMResult & {\n missingPromptIndices: number[];\n startedRunManagers?: CallbackManagerForLLMRun[];\n }\n > {\n const callbackManager_ = await CallbackManager.configure(\n handledOptions.callbacks,\n this.callbacks,\n handledOptions.tags,\n this.tags,\n handledOptions.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n const extra = {\n options: parsedOptions,\n invocation_params: this?.invocationParams(parsedOptions),\n batch_size: prompts.length,\n };\n const runManagers = await callbackManager_?.handleLLMStart(\n this.toJSON(),\n prompts,\n runId,\n undefined,\n extra,\n undefined,\n undefined,\n handledOptions?.runName\n );\n\n // generate results\n const missingPromptIndices: number[] = [];\n const results = await Promise.allSettled(\n prompts.map(async (prompt, index) => {\n const result = await cache.lookup(prompt, llmStringKey);\n if (result == null) {\n missingPromptIndices.push(index);\n }\n return result;\n })\n );\n\n // Map run managers to the results before filtering out null results\n // Null results are just absent from the cache.\n const cachedResults = results\n .map((result, index) => ({ result, runManager: runManagers?.[index] }))\n .filter(\n ({ result }) =>\n (result.status === \"fulfilled\" && result.value != null) ||\n result.status === \"rejected\"\n );\n\n // Handle results and call run managers\n const generations: Generation[][] = [];\n await Promise.all(\n cachedResults.map(async ({ result: promiseResult, runManager }, i) => {\n if (promiseResult.status === \"fulfilled\") {\n const result = promiseResult.value as Generation[];\n generations[i] = result.map((result) => {\n result.generationInfo = {\n ...result.generationInfo,\n tokenUsage: {},\n };\n return result;\n });\n if (result.length) {\n await runManager?.handleLLMNewToken(result[0].text);\n }\n return runManager?.handleLLMEnd(\n {\n generations: [result],\n },\n undefined,\n undefined,\n undefined,\n {\n cached: true,\n }\n );\n } else {\n // status === \"rejected\"\n await runManager?.handleLLMError(\n promiseResult.reason,\n undefined,\n undefined,\n undefined,\n {\n cached: true,\n }\n );\n return Promise.reject(promiseResult.reason);\n }\n })\n );\n\n const output = {\n generations,\n missingPromptIndices,\n startedRunManagers: runManagers,\n };\n\n // This defines RUN_KEY as a non-enumerable property on the output object\n // so that it is not serialized when the output is stringified, and so that\n // it isnt included when listing the keys of the output object.\n Object.defineProperty(output, RUN_KEY, {\n value: runManagers\n ? { runIds: runManagers?.map((manager) => manager.runId) }\n : undefined,\n configurable: true,\n });\n\n return output;\n }\n\n /**\n * Run the LLM on the given prompts and input, handling caching.\n */\n async generate(\n prompts: string[],\n options?: string[] | Partial<CallOptions>,\n callbacks?: Callbacks\n ): Promise<LLMResult> {\n if (!Array.isArray(prompts)) {\n throw new Error(\"Argument 'prompts' is expected to be a string[]\");\n }\n\n let parsedOptions: Partial<CallOptions> | undefined;\n if (Array.isArray(options)) {\n parsedOptions = { stop: options } as Partial<CallOptions>;\n } else {\n parsedOptions = options;\n }\n\n const [runnableConfig, callOptions] =\n this._separateRunnableConfigFromCallOptionsCompat(parsedOptions);\n runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks;\n\n if (!this.cache) {\n return this._generateUncached(prompts, callOptions, runnableConfig);\n }\n\n const { cache } = this;\n const llmStringKey = this._getSerializedCacheKeyParametersForCall(\n callOptions as CallOptions\n );\n const { generations, missingPromptIndices, startedRunManagers } =\n await this._generateCached({\n prompts,\n cache,\n llmStringKey,\n parsedOptions: callOptions,\n handledOptions: runnableConfig,\n runId: runnableConfig.runId,\n });\n\n let llmOutput = {};\n if (missingPromptIndices.length > 0) {\n const results = await this._generateUncached(\n missingPromptIndices.map((i) => prompts[i]),\n callOptions,\n runnableConfig,\n startedRunManagers !== undefined\n ? missingPromptIndices.map((i) => startedRunManagers?.[i])\n : undefined\n );\n await Promise.all(\n results.generations.map(async (generation, index) => {\n const promptIndex = missingPromptIndices[index];\n generations[promptIndex] = generation;\n return cache.update(prompts[promptIndex], llmStringKey, generation);\n })\n );\n llmOutput = results.llmOutput ?? {};\n }\n\n return { generations, llmOutput } as LLMResult;\n }\n\n /**\n * Get the identifying parameters of the LLM.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _identifyingParams(): Record<string, any> {\n return {};\n }\n\n /**\n * Return the string type key uniquely identifying this class of LLM.\n */\n abstract _llmType(): string;\n\n _modelType(): string {\n return \"base_llm\" as const;\n }\n}\n\n/**\n * LLM class that provides a simpler interface to subclass than {@link BaseLLM}.\n *\n * Requires only implementing a simpler {@link _call} method instead of {@link _generate}.\n *\n * @augments BaseLLM\n */\nexport abstract class LLM<\n CallOptions extends BaseLLMCallOptions = BaseLLMCallOptions,\n> extends BaseLLM<CallOptions> {\n /**\n * Run the LLM on the given prompt and input.\n */\n abstract _call(\n prompt: string,\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<string>;\n\n async _generate(\n prompts: string[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<LLMResult> {\n const generations: Generation[][] = await Promise.all(\n prompts.map((prompt, promptIndex) =>\n this._call(prompt, { ...options, promptIndex }, runManager).then(\n (text) => [{ text }]\n )\n )\n );\n return { generations };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqCA,IAAsB,UAAtB,MAAsB,gBAEZ,kBAAuC;CAQ/C,eAAe;EAAC;EAAa;EAAQ,KAAK,UAAU;CAAC;;;;;;;;;CAUrD,MAAM,OACJA,OACAC,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AMD,qBAA0C;AACxC,SAAO,CAAE;CACV;CAOD,aAAqB;AACnB,SAAO;CACR;AACF;;;;;;;;AASD,IAAsB,MAAtB,cAEU,QAAqB;CAU7B,MAAM,UACJb,SACAc,SACAC,YACoB;EACpB,MAAMJ,cAA8B,MAAM,QAAQ,IAChD,QAAQ,IAAI,CAAC,QAAQ,gBACnB,KAAK,MAAM,QAAQ;GAAE,GAAG;GAAS;EAAa,GAAE,WAAW,CAAC,KAC1D,CAAC,SAAS,CAAC,EAAE,KAAM,CAAC,EACrB,CACF,CACF;AACD,SAAO,EAAE,YAAa;CACvB;AACF"}
|
package/dist/load/import_map.cjs
CHANGED
|
@@ -2,6 +2,7 @@ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
|
2
2
|
const require_agents = require('../agents.cjs');
|
|
3
3
|
const require_load_serializable = require('./serializable.cjs');
|
|
4
4
|
const require_messages_tool = require('../messages/tool.cjs');
|
|
5
|
+
const require_errors_index = require('../errors/index.cjs');
|
|
5
6
|
const require_utils_env = require('../utils/env.cjs');
|
|
6
7
|
const require_callbacks_base = require('../callbacks/base.cjs');
|
|
7
8
|
const require_tracers_base = require('../tracers/base.cjs');
|
|
@@ -70,6 +71,7 @@ require_rolldown_runtime.__export(import_map_exports, {
|
|
|
70
71
|
document_loaders__langsmith: () => require_document_loaders_langsmith.langsmith_exports,
|
|
71
72
|
documents: () => require_documents_index.documents_exports,
|
|
72
73
|
embeddings: () => require_embeddings.embeddings_exports,
|
|
74
|
+
errors: () => require_errors_index.errors_exports,
|
|
73
75
|
example_selectors: () => require_example_selectors_index.example_selectors_exports,
|
|
74
76
|
index: () => require_index.src_exports,
|
|
75
77
|
indexing: () => require_indexing_index.indexing_exports,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"import_map.cjs","names":[],"sources":["../../src/load/import_map.ts"],"sourcesContent":["/** Auto-generated by import-map plugin. Do not edit manually */\n\nexport * as agents from \"../agents.js\";\nexport * as caches from \"../caches/index.js\";\nexport * as callbacks__base from \"../callbacks/base.js\";\nexport * as callbacks__manager from \"../callbacks/manager.js\";\nexport * as callbacks__promises from \"../callbacks/promises.js\";\nexport * as chat_history from \"../chat_history.js\";\nexport * as document_loaders__base from \"../document_loaders/base.js\";\nexport * as document_loaders__langsmith from \"../document_loaders/langsmith.js\";\nexport * as documents from \"../documents/index.js\";\nexport * as embeddings from \"../embeddings.js\";\nexport * as example_selectors from \"../example_selectors/index.js\";\nexport * as index from \"../index.js\";\nexport * as indexing from \"../indexing/index.js\";\nexport * as language_models__base from \"../language_models/base.js\";\nexport * as language_models__chat_models from \"../language_models/chat_models.js\";\nexport * as language_models__llms from \"../language_models/llms.js\";\nexport * as language_models__profile from \"../language_models/profile.js\";\nexport * as load__serializable from \"../load/serializable.js\";\nexport * as memory from \"../memory.js\";\nexport * as messages from \"../messages/index.js\";\nexport * as messages__tool from \"../messages/tool.js\";\nexport * as output_parsers from \"../output_parsers/index.js\";\nexport * as output_parsers__openai_functions from \"../output_parsers/openai_functions/index.js\";\nexport * as output_parsers__openai_tools from \"../output_parsers/openai_tools/index.js\";\nexport * as outputs from \"../outputs.js\";\nexport * as prompt_values from \"../prompt_values.js\";\nexport * as prompts from \"../prompts/index.js\";\nexport * as retrievers__document_compressors from \"../retrievers/document_compressors/index.js\";\nexport * as retrievers from \"../retrievers/index.js\";\nexport * as runnables__graph from \"../runnables/graph.js\";\nexport * as runnables from \"../runnables/index.js\";\nexport * as singletons from \"../singletons/index.js\";\nexport * as stores from \"../stores.js\";\nexport * as structured_query from \"../structured_query/index.js\";\nexport * as tools from \"../tools/index.js\";\nexport * as tracers__base from \"../tracers/base.js\";\nexport * as tracers__console from \"../tracers/console.js\";\nexport * as tracers__log_stream from \"../tracers/log_stream.js\";\nexport * as tracers__run_collector from \"../tracers/run_collector.js\";\nexport * as tracers__tracer_langchain from \"../tracers/tracer_langchain.js\";\nexport * as types__stream from \"../types/stream.js\";\nexport * as utils__async_caller from \"../utils/async_caller.js\";\nexport * as utils__chunk_array from \"../utils/chunk_array.js\";\nexport * as utils__context from \"../utils/context.js\";\nexport * as utils__env from \"../utils/env.js\";\nexport * as utils__event_source_parse from \"../utils/event_source_parse.js\";\nexport * as utils__format from \"../utils/format.js\";\nexport * as utils__function_calling from \"../utils/function_calling.js\";\nexport * as utils__hash from \"../utils/hash.js\";\nexport * as utils__json_patch from \"../utils/json_patch.js\";\nexport * as utils__json_schema from \"../utils/json_schema.js\";\nexport * as utils__math from \"../utils/math.js\";\nexport * as utils__stream from \"../utils/stream.js\";\nexport * as utils__testing from \"../utils/testing/index.js\";\nexport * as utils__tiktoken from \"../utils/tiktoken.js\";\nexport * as utils__types from \"../utils/types/index.js\";\nexport * as vectorstores from \"../vectorstores.js\";\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"import_map.cjs","names":[],"sources":["../../src/load/import_map.ts"],"sourcesContent":["/** Auto-generated by import-map plugin. Do not edit manually */\n\nexport * as agents from \"../agents.js\";\nexport * as caches from \"../caches/index.js\";\nexport * as callbacks__base from \"../callbacks/base.js\";\nexport * as callbacks__manager from \"../callbacks/manager.js\";\nexport * as callbacks__promises from \"../callbacks/promises.js\";\nexport * as chat_history from \"../chat_history.js\";\nexport * as document_loaders__base from \"../document_loaders/base.js\";\nexport * as document_loaders__langsmith from \"../document_loaders/langsmith.js\";\nexport * as documents from \"../documents/index.js\";\nexport * as embeddings from \"../embeddings.js\";\nexport * as errors from \"../errors/index.js\";\nexport * as example_selectors from \"../example_selectors/index.js\";\nexport * as index from \"../index.js\";\nexport * as indexing from \"../indexing/index.js\";\nexport * as language_models__base from \"../language_models/base.js\";\nexport * as language_models__chat_models from \"../language_models/chat_models.js\";\nexport * as language_models__llms from \"../language_models/llms.js\";\nexport * as language_models__profile from \"../language_models/profile.js\";\nexport * as load__serializable from \"../load/serializable.js\";\nexport * as memory from \"../memory.js\";\nexport * as messages from \"../messages/index.js\";\nexport * as messages__tool from \"../messages/tool.js\";\nexport * as output_parsers from \"../output_parsers/index.js\";\nexport * as output_parsers__openai_functions from \"../output_parsers/openai_functions/index.js\";\nexport * as output_parsers__openai_tools from \"../output_parsers/openai_tools/index.js\";\nexport * as outputs from \"../outputs.js\";\nexport * as prompt_values from \"../prompt_values.js\";\nexport * as prompts from \"../prompts/index.js\";\nexport * as retrievers__document_compressors from \"../retrievers/document_compressors/index.js\";\nexport * as retrievers from \"../retrievers/index.js\";\nexport * as runnables__graph from \"../runnables/graph.js\";\nexport * as runnables from \"../runnables/index.js\";\nexport * as singletons from \"../singletons/index.js\";\nexport * as stores from \"../stores.js\";\nexport * as structured_query from \"../structured_query/index.js\";\nexport * as tools from \"../tools/index.js\";\nexport * as tracers__base from \"../tracers/base.js\";\nexport * as tracers__console from \"../tracers/console.js\";\nexport * as tracers__log_stream from \"../tracers/log_stream.js\";\nexport * as tracers__run_collector from \"../tracers/run_collector.js\";\nexport * as tracers__tracer_langchain from \"../tracers/tracer_langchain.js\";\nexport * as types__stream from \"../types/stream.js\";\nexport * as utils__async_caller from \"../utils/async_caller.js\";\nexport * as utils__chunk_array from \"../utils/chunk_array.js\";\nexport * as utils__context from \"../utils/context.js\";\nexport * as utils__env from \"../utils/env.js\";\nexport * as utils__event_source_parse from \"../utils/event_source_parse.js\";\nexport * as utils__format from \"../utils/format.js\";\nexport * as utils__function_calling from \"../utils/function_calling.js\";\nexport * as utils__hash from \"../utils/hash.js\";\nexport * as utils__json_patch from \"../utils/json_patch.js\";\nexport * as utils__json_schema from \"../utils/json_schema.js\";\nexport * as utils__math from \"../utils/math.js\";\nexport * as utils__stream from \"../utils/stream.js\";\nexport * as utils__testing from \"../utils/testing/index.js\";\nexport * as utils__tiktoken from \"../utils/tiktoken.js\";\nexport * as utils__types from \"../utils/types/index.js\";\nexport * as vectorstores from \"../vectorstores.js\";\n"],"mappings":""}
|
package/dist/load/import_map.js
CHANGED
|
@@ -2,6 +2,7 @@ import { __export } from "../_virtual/rolldown_runtime.js";
|
|
|
2
2
|
import { agents_exports } from "../agents.js";
|
|
3
3
|
import { serializable_exports } from "./serializable.js";
|
|
4
4
|
import { tool_exports } from "../messages/tool.js";
|
|
5
|
+
import { errors_exports } from "../errors/index.js";
|
|
5
6
|
import { env_exports } from "../utils/env.js";
|
|
6
7
|
import { base_exports } from "../callbacks/base.js";
|
|
7
8
|
import { base_exports as base_exports$1 } from "../tracers/base.js";
|
|
@@ -70,6 +71,7 @@ __export(import_map_exports, {
|
|
|
70
71
|
document_loaders__langsmith: () => langsmith_exports,
|
|
71
72
|
documents: () => documents_exports,
|
|
72
73
|
embeddings: () => embeddings_exports,
|
|
74
|
+
errors: () => errors_exports,
|
|
73
75
|
example_selectors: () => example_selectors_exports,
|
|
74
76
|
index: () => src_exports,
|
|
75
77
|
indexing: () => indexing_exports,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"import_map.js","names":[],"sources":["../../src/load/import_map.ts"],"sourcesContent":["/** Auto-generated by import-map plugin. Do not edit manually */\n\nexport * as agents from \"../agents.js\";\nexport * as caches from \"../caches/index.js\";\nexport * as callbacks__base from \"../callbacks/base.js\";\nexport * as callbacks__manager from \"../callbacks/manager.js\";\nexport * as callbacks__promises from \"../callbacks/promises.js\";\nexport * as chat_history from \"../chat_history.js\";\nexport * as document_loaders__base from \"../document_loaders/base.js\";\nexport * as document_loaders__langsmith from \"../document_loaders/langsmith.js\";\nexport * as documents from \"../documents/index.js\";\nexport * as embeddings from \"../embeddings.js\";\nexport * as example_selectors from \"../example_selectors/index.js\";\nexport * as index from \"../index.js\";\nexport * as indexing from \"../indexing/index.js\";\nexport * as language_models__base from \"../language_models/base.js\";\nexport * as language_models__chat_models from \"../language_models/chat_models.js\";\nexport * as language_models__llms from \"../language_models/llms.js\";\nexport * as language_models__profile from \"../language_models/profile.js\";\nexport * as load__serializable from \"../load/serializable.js\";\nexport * as memory from \"../memory.js\";\nexport * as messages from \"../messages/index.js\";\nexport * as messages__tool from \"../messages/tool.js\";\nexport * as output_parsers from \"../output_parsers/index.js\";\nexport * as output_parsers__openai_functions from \"../output_parsers/openai_functions/index.js\";\nexport * as output_parsers__openai_tools from \"../output_parsers/openai_tools/index.js\";\nexport * as outputs from \"../outputs.js\";\nexport * as prompt_values from \"../prompt_values.js\";\nexport * as prompts from \"../prompts/index.js\";\nexport * as retrievers__document_compressors from \"../retrievers/document_compressors/index.js\";\nexport * as retrievers from \"../retrievers/index.js\";\nexport * as runnables__graph from \"../runnables/graph.js\";\nexport * as runnables from \"../runnables/index.js\";\nexport * as singletons from \"../singletons/index.js\";\nexport * as stores from \"../stores.js\";\nexport * as structured_query from \"../structured_query/index.js\";\nexport * as tools from \"../tools/index.js\";\nexport * as tracers__base from \"../tracers/base.js\";\nexport * as tracers__console from \"../tracers/console.js\";\nexport * as tracers__log_stream from \"../tracers/log_stream.js\";\nexport * as tracers__run_collector from \"../tracers/run_collector.js\";\nexport * as tracers__tracer_langchain from \"../tracers/tracer_langchain.js\";\nexport * as types__stream from \"../types/stream.js\";\nexport * as utils__async_caller from \"../utils/async_caller.js\";\nexport * as utils__chunk_array from \"../utils/chunk_array.js\";\nexport * as utils__context from \"../utils/context.js\";\nexport * as utils__env from \"../utils/env.js\";\nexport * as utils__event_source_parse from \"../utils/event_source_parse.js\";\nexport * as utils__format from \"../utils/format.js\";\nexport * as utils__function_calling from \"../utils/function_calling.js\";\nexport * as utils__hash from \"../utils/hash.js\";\nexport * as utils__json_patch from \"../utils/json_patch.js\";\nexport * as utils__json_schema from \"../utils/json_schema.js\";\nexport * as utils__math from \"../utils/math.js\";\nexport * as utils__stream from \"../utils/stream.js\";\nexport * as utils__testing from \"../utils/testing/index.js\";\nexport * as utils__tiktoken from \"../utils/tiktoken.js\";\nexport * as utils__types from \"../utils/types/index.js\";\nexport * as vectorstores from \"../vectorstores.js\";\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"import_map.js","names":[],"sources":["../../src/load/import_map.ts"],"sourcesContent":["/** Auto-generated by import-map plugin. Do not edit manually */\n\nexport * as agents from \"../agents.js\";\nexport * as caches from \"../caches/index.js\";\nexport * as callbacks__base from \"../callbacks/base.js\";\nexport * as callbacks__manager from \"../callbacks/manager.js\";\nexport * as callbacks__promises from \"../callbacks/promises.js\";\nexport * as chat_history from \"../chat_history.js\";\nexport * as document_loaders__base from \"../document_loaders/base.js\";\nexport * as document_loaders__langsmith from \"../document_loaders/langsmith.js\";\nexport * as documents from \"../documents/index.js\";\nexport * as embeddings from \"../embeddings.js\";\nexport * as errors from \"../errors/index.js\";\nexport * as example_selectors from \"../example_selectors/index.js\";\nexport * as index from \"../index.js\";\nexport * as indexing from \"../indexing/index.js\";\nexport * as language_models__base from \"../language_models/base.js\";\nexport * as language_models__chat_models from \"../language_models/chat_models.js\";\nexport * as language_models__llms from \"../language_models/llms.js\";\nexport * as language_models__profile from \"../language_models/profile.js\";\nexport * as load__serializable from \"../load/serializable.js\";\nexport * as memory from \"../memory.js\";\nexport * as messages from \"../messages/index.js\";\nexport * as messages__tool from \"../messages/tool.js\";\nexport * as output_parsers from \"../output_parsers/index.js\";\nexport * as output_parsers__openai_functions from \"../output_parsers/openai_functions/index.js\";\nexport * as output_parsers__openai_tools from \"../output_parsers/openai_tools/index.js\";\nexport * as outputs from \"../outputs.js\";\nexport * as prompt_values from \"../prompt_values.js\";\nexport * as prompts from \"../prompts/index.js\";\nexport * as retrievers__document_compressors from \"../retrievers/document_compressors/index.js\";\nexport * as retrievers from \"../retrievers/index.js\";\nexport * as runnables__graph from \"../runnables/graph.js\";\nexport * as runnables from \"../runnables/index.js\";\nexport * as singletons from \"../singletons/index.js\";\nexport * as stores from \"../stores.js\";\nexport * as structured_query from \"../structured_query/index.js\";\nexport * as tools from \"../tools/index.js\";\nexport * as tracers__base from \"../tracers/base.js\";\nexport * as tracers__console from \"../tracers/console.js\";\nexport * as tracers__log_stream from \"../tracers/log_stream.js\";\nexport * as tracers__run_collector from \"../tracers/run_collector.js\";\nexport * as tracers__tracer_langchain from \"../tracers/tracer_langchain.js\";\nexport * as types__stream from \"../types/stream.js\";\nexport * as utils__async_caller from \"../utils/async_caller.js\";\nexport * as utils__chunk_array from \"../utils/chunk_array.js\";\nexport * as utils__context from \"../utils/context.js\";\nexport * as utils__env from \"../utils/env.js\";\nexport * as utils__event_source_parse from \"../utils/event_source_parse.js\";\nexport * as utils__format from \"../utils/format.js\";\nexport * as utils__function_calling from \"../utils/function_calling.js\";\nexport * as utils__hash from \"../utils/hash.js\";\nexport * as utils__json_patch from \"../utils/json_patch.js\";\nexport * as utils__json_schema from \"../utils/json_schema.js\";\nexport * as utils__math from \"../utils/math.js\";\nexport * as utils__stream from \"../utils/stream.js\";\nexport * as utils__testing from \"../utils/testing/index.js\";\nexport * as utils__tiktoken from \"../utils/tiktoken.js\";\nexport * as utils__types from \"../utils/types/index.js\";\nexport * as vectorstores from \"../vectorstores.js\";\n"],"mappings":""}
|
package/dist/memory.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory.d.cts","names":["InputValues","Record","OutputValues","MemoryVariables","BaseMemory","Promise","getInputValue","getOutputValue","getPromptInputKey"],"sources":["../src/memory.d.ts"],"sourcesContent":["/**\n * Type alias for a record where the keys are strings and the values can\n * be any type. This is used to represent the input values for a Chain.\n */\nexport type InputValues = Record<string, any>;\n/**\n * Type alias for a record where the keys are strings and the values can\n * be any type. This is used to represent the output values from a Chain.\n */\nexport type OutputValues = Record<string, any>;\n/**\n * Type alias for a record where the keys are strings and the values can\n * be any type. This is used to represent the memory variables in a Chain.\n */\nexport type MemoryVariables = Record<string, any>;\n/**\n * Abstract base class for memory in LangChain's Chains. Memory refers to\n * the state in Chains. It can be used to store information about past\n * executions of a Chain and inject that information into the inputs of\n * future executions of the Chain.\n */\nexport declare abstract class BaseMemory {\n abstract get memoryKeys(): string[];\n /**\n * Abstract method that should take an object of input values and return a\n * Promise that resolves with an object of memory variables. The\n * implementation of this method should load the memory variables from the\n * provided input values.\n * @param values An object of input values.\n * @returns Promise that resolves with an object of memory variables.\n */\n abstract loadMemoryVariables(values: InputValues): Promise<MemoryVariables>;\n /**\n * Abstract method that should take two objects, one of input values and\n * one of output values, and return a Promise that resolves when the\n * context has been saved. The implementation of this method should save\n * the context based on the provided input and output values.\n * @param inputValues An object of input values.\n * @param outputValues An object of output values.\n * @returns Promise that resolves when the context has been saved.\n */\n abstract saveContext(inputValues: InputValues, outputValues: OutputValues): Promise<void>;\n}\n/**\n * This function is used by memory classes to select the input value\n * to use for the memory. If there is only one input value, it is used.\n * If there are multiple input values, the inputKey must be specified.\n */\nexport declare const getInputValue: (inputValues: InputValues, inputKey?: string | undefined) => any;\n/**\n * This function is used by memory classes to select the output value\n * to use for the memory. If there is only one output value, it is used.\n * If there are multiple output values, the outputKey must be specified.\n * If no outputKey is specified, an error is thrown.\n */\nexport declare const getOutputValue: (outputValues: OutputValues, outputKey?: string | undefined) => any;\n/**\n * Function used by memory classes to get the key of the prompt input,\n * excluding any keys that are memory variables or the \"stop\" key. If\n * there is not exactly one prompt input key, an error is thrown.\n */\nexport declare function getPromptInputKey(inputs: Record<string, unknown>, memoryVariables: string[]): string;\n//# sourceMappingURL=memory.d.ts.map"],"mappings":";;AAIA;AAKA;AAKA;AAO8BI,KAjBlBJ,WAAAA,GAAcC,MAiBc,CAAA,MAAA,EAAA,GAAA,CAAA;;;;;AAoByBC,KAhCrDA,YAAAA,GAAeD,MAgCsCC,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA;;AAAsB;AAOvF;AAOA;AAMwBM,KA/CZL,eAAAA,GAAkBF,MA+
|
|
1
|
+
{"version":3,"file":"memory.d.cts","names":["InputValues","Record","OutputValues","MemoryVariables","BaseMemory","Promise","getInputValue","getOutputValue","getPromptInputKey"],"sources":["../src/memory.d.ts"],"sourcesContent":["/**\n * Type alias for a record where the keys are strings and the values can\n * be any type. This is used to represent the input values for a Chain.\n */\nexport type InputValues = Record<string, any>;\n/**\n * Type alias for a record where the keys are strings and the values can\n * be any type. This is used to represent the output values from a Chain.\n */\nexport type OutputValues = Record<string, any>;\n/**\n * Type alias for a record where the keys are strings and the values can\n * be any type. This is used to represent the memory variables in a Chain.\n */\nexport type MemoryVariables = Record<string, any>;\n/**\n * Abstract base class for memory in LangChain's Chains. Memory refers to\n * the state in Chains. It can be used to store information about past\n * executions of a Chain and inject that information into the inputs of\n * future executions of the Chain.\n */\nexport declare abstract class BaseMemory {\n abstract get memoryKeys(): string[];\n /**\n * Abstract method that should take an object of input values and return a\n * Promise that resolves with an object of memory variables. The\n * implementation of this method should load the memory variables from the\n * provided input values.\n * @param values An object of input values.\n * @returns Promise that resolves with an object of memory variables.\n */\n abstract loadMemoryVariables(values: InputValues): Promise<MemoryVariables>;\n /**\n * Abstract method that should take two objects, one of input values and\n * one of output values, and return a Promise that resolves when the\n * context has been saved. The implementation of this method should save\n * the context based on the provided input and output values.\n * @param inputValues An object of input values.\n * @param outputValues An object of output values.\n * @returns Promise that resolves when the context has been saved.\n */\n abstract saveContext(inputValues: InputValues, outputValues: OutputValues): Promise<void>;\n}\n/**\n * This function is used by memory classes to select the input value\n * to use for the memory. If there is only one input value, it is used.\n * If there are multiple input values, the inputKey must be specified.\n */\nexport declare const getInputValue: (inputValues: InputValues, inputKey?: string | undefined) => any;\n/**\n * This function is used by memory classes to select the output value\n * to use for the memory. If there is only one output value, it is used.\n * If there are multiple output values, the outputKey must be specified.\n * If no outputKey is specified, an error is thrown.\n */\nexport declare const getOutputValue: (outputValues: OutputValues, outputKey?: string | undefined) => any;\n/**\n * Function used by memory classes to get the key of the prompt input,\n * excluding any keys that are memory variables or the \"stop\" key. If\n * there is not exactly one prompt input key, an error is thrown.\n */\nexport declare function getPromptInputKey(inputs: Record<string, unknown>, memoryVariables: string[]): string;\n//# sourceMappingURL=memory.d.ts.map"],"mappings":";;AAIA;AAKA;AAKA;AAO8BI,KAjBlBJ,WAAAA,GAAcC,MAiBc,CAAA,MAAA,EAAA,GAAA,CAAA;;;;;AAoByBC,KAhCrDA,YAAAA,GAAeD,MAgCsCC,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA;;AAAsB;AAOvF;AAOA;AAMwBM,KA/CZL,eAAAA,GAAkBF,MA+CW,CAASA,MAAM,EAAA,GAAA,CAAA;;;;;;;uBAxC1BG,UAAAA;;;;;;;;;;uCAUWJ,cAAcK,QAAQF;;;;;;;;;;oCAUzBH,2BAA2BE,eAAeG;;;;;;;cAO3DC,6BAA6BN;;;;;;;cAO7BO,+BAA+BL;;;;;;iBAM5BM,iBAAAA,SAA0BP"}
|
package/dist/messages/utils.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const require_base = require('./base.cjs');
|
|
2
2
|
const require_messages_tool = require('./tool.cjs');
|
|
3
|
-
const
|
|
3
|
+
const require_errors_index = require('../errors/index.cjs');
|
|
4
4
|
const require_utils = require('../tools/utils.cjs');
|
|
5
5
|
const require_json = require('../utils/json.cjs');
|
|
6
6
|
const require_chat = require('./chat.cjs');
|
|
@@ -76,7 +76,7 @@ function _constructMessageFromParams(params) {
|
|
|
76
76
|
id: rest.id
|
|
77
77
|
});
|
|
78
78
|
else {
|
|
79
|
-
const error =
|
|
79
|
+
const error = require_errors_index.addLangChainErrorFields(/* @__PURE__ */ new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(params, null, 2)}`), "MESSAGE_COERCION_FAILURE");
|
|
80
80
|
throw error;
|
|
81
81
|
}
|
|
82
82
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","names":["fn: () => T","toolCall: ToolCall | Record<string, unknown>","_isToolCall","x: unknown","params:\n | (BaseMessageFields & { type: string } & Record<string, unknown>)\n | SerializedConstructor","type: string","rest: BaseMessageFields & Record<string, unknown>","HumanMessage","AIMessage","SystemMessage","ToolMessage","RemoveMessage","addLangChainErrorFields","messageLike: BaseMessageLike","isBaseMessage","_isMessageFieldWithRole","messages: BaseMessage[]","string_messages: string[]","role: string","message: StoredMessage | StoredMessageV1","message: StoredMessage","FunctionMessage","ChatMessage","messages: StoredMessage[]","message: BaseMessage","HumanMessageChunk","aiChunkFields: AIMessageChunkFields","AIMessageChunk","SystemMessageChunk","FunctionMessageChunk","ChatMessageChunk","chunks: ToolCallChunk[]","toolCalls: ToolCall[]","invalidToolCalls: InvalidToolCall[]","chunks","parsedArgs: Record<string, unknown> | null","parsePartialJson"],"sources":["../../src/messages/utils.ts"],"sourcesContent":["import { addLangChainErrorFields } from \"../errors/index.js\";\nimport { SerializedConstructor } from \"../load/serializable.js\";\nimport { _isToolCall } from \"../tools/utils.js\";\nimport { parsePartialJson } from \"../utils/json.js\";\nimport { AIMessage, AIMessageChunk, AIMessageChunkFields } from \"./ai.js\";\nimport {\n BaseMessageLike,\n BaseMessage,\n isBaseMessage,\n StoredMessage,\n StoredMessageV1,\n BaseMessageFields,\n _isMessageFieldWithRole,\n} from \"./base.js\";\nimport { ChatMessage, ChatMessageFields, ChatMessageChunk } from \"./chat.js\";\nimport {\n FunctionMessage,\n FunctionMessageChunk,\n FunctionMessageFields,\n} from \"./function.js\";\nimport { HumanMessage, HumanMessageChunk } from \"./human.js\";\nimport { RemoveMessage } from \"./modifier.js\";\nimport { SystemMessage, SystemMessageChunk } from \"./system.js\";\nimport {\n InvalidToolCall,\n ToolCall,\n ToolCallChunk,\n ToolMessage,\n ToolMessageFields,\n} from \"./tool.js\";\n\nexport type $Expand<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;\n\n/**\n * Extracts the explicitly declared keys from a type T.\n *\n * @template T - The type to extract keys from\n * @returns A union of keys that are not string, number, or symbol\n */\ntype $KnownKeys<T> = {\n [K in keyof T]: string extends K\n ? never\n : number extends K\n ? never\n : symbol extends K\n ? never\n : K;\n}[keyof T];\n\n/**\n * Detects if T has an index signature.\n *\n * @template T - The type to check for index signatures\n * @returns True if T has an index signature, false otherwise\n */\ntype $HasIndexSignature<T> = string extends keyof T\n ? true\n : number extends keyof T\n ? true\n : symbol extends keyof T\n ? true\n : false;\n\n/**\n * Detects if T has an index signature and no known keys.\n *\n * @template T - The type to check for index signatures and no known keys\n * @returns True if T has an index signature and no known keys, false otherwise\n */\ntype $OnlyIndexSignatures<T> =\n $HasIndexSignature<T> extends true\n ? [$KnownKeys<T>] extends [never]\n ? true\n : false\n : false;\n\n/**\n * Recursively merges two object types T and U, with U taking precedence over T.\n *\n * This utility type performs a deep merge of two object types:\n * - For keys that exist in both T and U:\n * - If both values are objects (Record<string, unknown>), recursively merge them\n * - Otherwise, U's value takes precedence\n * - For keys that exist only in T, use T's value\n * - For keys that exist only in U, use U's value\n *\n * @template T - The first object type to merge\n * @template U - The second object type to merge (takes precedence over T)\n *\n * @example\n * ```ts\n * type ObjectA = {\n * shared: { a: string; b: number };\n * onlyInA: boolean;\n * };\n *\n * type ObjectB = {\n * shared: { b: string; c: Date };\n * onlyInB: symbol;\n * };\n *\n * type Merged = $MergeObjects<ObjectA, ObjectB>;\n * // Result: {\n * // shared: { a: string; b: string; c: Date };\n * // onlyInA: boolean;\n * // onlyInB: symbol;\n * // }\n * ```\n */\nexport type $MergeObjects<T, U> =\n // If U is purely index-signature based, prefer U as a whole\n $OnlyIndexSignatures<U> extends true\n ? U\n : // If T is purely index-signature based, prefer U as a whole (prevents leaking broad index signatures)\n $OnlyIndexSignatures<T> extends true\n ? U\n : {\n [K in keyof T | keyof U]: K extends keyof T\n ? K extends keyof U\n ? T[K] extends Record<string, unknown>\n ? U[K] extends Record<string, unknown>\n ? $MergeObjects<T[K], U[K]>\n : U[K]\n : U[K]\n : T[K]\n : K extends keyof U\n ? U[K]\n : never;\n };\n\n/**\n * Merges two discriminated unions A and B based on a discriminator key (defaults to \"type\").\n * For each possible value of the discriminator across both unions:\n * - If B has a member with that discriminator value, use B's member\n * - Otherwise use A's member with that discriminator value\n * This effectively merges the unions while giving B's members precedence over A's members.\n *\n * @template A - First discriminated union type that extends Record<Key, PropertyKey>\n * @template B - Second discriminated union type that extends Record<Key, PropertyKey>\n * @template Key - The discriminator key property, defaults to \"type\"\n */\nexport type $MergeDiscriminatedUnion<\n A extends Record<Key, PropertyKey>,\n B extends Record<Key, PropertyKey>,\n Key extends PropertyKey = \"type\",\n> = {\n // Create a mapped type over all possible discriminator values from both A and B\n [T in A[Key] | B[Key]]: [Extract<B, Record<Key, T>>] extends [never] // Check if B has a member with this discriminator value\n ? // If B doesn't have this discriminator value, use A's member\n Extract<A, Record<Key, T>>\n : // If B does have this discriminator value, merge A's and B's members (B takes precedence)\n [Extract<A, Record<Key, T>>] extends [never]\n ? Extract<B, Record<Key, T>>\n : $MergeObjects<Extract<A, Record<Key, T>>, Extract<B, Record<Key, T>>>;\n // Index into the mapped type with all possible discriminator values\n // This converts the mapped type back into a union\n}[A[Key] | B[Key]];\n\nexport type Constructor<T> = new (...args: unknown[]) => T;\n\n/**\n * Immediately-invoked function expression.\n *\n * @param fn - The function to execute\n * @returns The result of the function\n */\nexport const iife = <T>(fn: () => T) => fn();\n\nfunction _coerceToolCall(\n toolCall: ToolCall | Record<string, unknown>\n): ToolCall {\n if (_isToolCall(toolCall)) {\n return toolCall;\n } else if (\n typeof toolCall.id === \"string\" &&\n toolCall.type === \"function\" &&\n typeof toolCall.function === \"object\" &&\n toolCall.function !== null &&\n \"arguments\" in toolCall.function &&\n typeof toolCall.function.arguments === \"string\" &&\n \"name\" in toolCall.function &&\n typeof toolCall.function.name === \"string\"\n ) {\n // Handle OpenAI tool call format\n return {\n id: toolCall.id,\n args: JSON.parse(toolCall.function.arguments),\n name: toolCall.function.name,\n type: \"tool_call\",\n };\n } else {\n // TODO: Throw an error?\n return toolCall as unknown as ToolCall;\n }\n}\n\nfunction isSerializedConstructor(x: unknown): x is SerializedConstructor {\n return (\n typeof x === \"object\" &&\n x != null &&\n (x as SerializedConstructor).lc === 1 &&\n Array.isArray((x as SerializedConstructor).id) &&\n (x as SerializedConstructor).kwargs != null &&\n typeof (x as SerializedConstructor).kwargs === \"object\"\n );\n}\n\nfunction _constructMessageFromParams(\n params:\n | (BaseMessageFields & { type: string } & Record<string, unknown>)\n | SerializedConstructor\n) {\n let type: string;\n let rest: BaseMessageFields & Record<string, unknown>;\n // Support serialized messages\n if (isSerializedConstructor(params)) {\n const className = params.id.at(-1);\n if (className === \"HumanMessage\" || className === \"HumanMessageChunk\") {\n type = \"user\";\n } else if (className === \"AIMessage\" || className === \"AIMessageChunk\") {\n type = \"assistant\";\n } else if (\n className === \"SystemMessage\" ||\n className === \"SystemMessageChunk\"\n ) {\n type = \"system\";\n } else if (\n className === \"FunctionMessage\" ||\n className === \"FunctionMessageChunk\"\n ) {\n type = \"function\";\n } else if (\n className === \"ToolMessage\" ||\n className === \"ToolMessageChunk\"\n ) {\n type = \"tool\";\n } else {\n type = \"unknown\";\n }\n rest = params.kwargs as BaseMessageFields;\n } else {\n const { type: extractedType, ...otherParams } = params;\n type = extractedType;\n rest = otherParams;\n }\n if (type === \"human\" || type === \"user\") {\n return new HumanMessage(rest);\n } else if (type === \"ai\" || type === \"assistant\") {\n const { tool_calls: rawToolCalls, ...other } = rest;\n if (!Array.isArray(rawToolCalls)) {\n return new AIMessage(rest);\n }\n const tool_calls = rawToolCalls.map(_coerceToolCall);\n return new AIMessage({ ...other, tool_calls });\n } else if (type === \"system\") {\n return new SystemMessage(rest);\n } else if (type === \"developer\") {\n return new SystemMessage({\n ...rest,\n additional_kwargs: {\n ...rest.additional_kwargs,\n __openai_role__: \"developer\",\n },\n });\n } else if (type === \"tool\" && \"tool_call_id\" in rest) {\n return new ToolMessage({\n ...rest,\n content: rest.content,\n tool_call_id: rest.tool_call_id as string,\n name: rest.name,\n });\n } else if (type === \"remove\" && \"id\" in rest && typeof rest.id === \"string\") {\n return new RemoveMessage({ ...rest, id: rest.id });\n } else {\n const error = addLangChainErrorFields(\n new Error(\n `Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\\n\\nReceived: ${JSON.stringify(\n params,\n null,\n 2\n )}`\n ),\n \"MESSAGE_COERCION_FAILURE\"\n );\n throw error;\n }\n}\n\nexport function coerceMessageLikeToMessage(\n messageLike: BaseMessageLike\n): BaseMessage {\n if (typeof messageLike === \"string\") {\n return new HumanMessage(messageLike);\n } else if (isBaseMessage(messageLike)) {\n return messageLike;\n }\n if (Array.isArray(messageLike)) {\n const [type, content] = messageLike;\n return _constructMessageFromParams({ type, content });\n } else if (_isMessageFieldWithRole(messageLike)) {\n const { role: type, ...rest } = messageLike;\n return _constructMessageFromParams({ ...rest, type });\n } else {\n return _constructMessageFromParams(messageLike);\n }\n}\n\n/**\n * This function is used by memory classes to get a string representation\n * of the chat message history, based on the message content and role.\n *\n * Produces compact output like:\n * ```\n * Human: What's the weather?\n * AI: Let me check...[tool_calls]\n * Tool: 72°F and sunny\n * ```\n *\n * This avoids token inflation from metadata when stringifying message objects directly.\n */\nexport function getBufferString(\n messages: BaseMessage[],\n humanPrefix = \"Human\",\n aiPrefix = \"AI\"\n): string {\n const string_messages: string[] = [];\n for (const m of messages) {\n let role: string;\n if (m.type === \"human\") {\n role = humanPrefix;\n } else if (m.type === \"ai\") {\n role = aiPrefix;\n } else if (m.type === \"system\") {\n role = \"System\";\n } else if (m.type === \"tool\") {\n role = \"Tool\";\n } else if (m.type === \"generic\") {\n role = (m as ChatMessage).role;\n } else {\n throw new Error(`Got unsupported message type: ${m.type}`);\n }\n const nameStr = m.name ? `${m.name}, ` : \"\";\n\n // Use m.text property which extracts only text content, avoiding metadata\n // For non-string content (e.g., content blocks), m.text extracts only text blocks\n const readableContent = m.text;\n\n let message = `${role}: ${nameStr}${readableContent}`;\n\n // Include tool calls for AI messages (matching Python's get_buffer_string behavior)\n if (m.type === \"ai\") {\n const aiMessage = m as AIMessage;\n if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {\n message += JSON.stringify(aiMessage.tool_calls);\n } else if (\n aiMessage.additional_kwargs &&\n \"function_call\" in aiMessage.additional_kwargs\n ) {\n // Legacy behavior assumes only one function call per message\n message += JSON.stringify(aiMessage.additional_kwargs.function_call);\n }\n }\n\n string_messages.push(message);\n }\n return string_messages.join(\"\\n\");\n}\n\n/**\n * Maps messages from an older format (V1) to the current `StoredMessage`\n * format. If the message is already in the `StoredMessage` format, it is\n * returned as is. Otherwise, it transforms the V1 message into a\n * `StoredMessage`. This function is important for maintaining\n * compatibility with older message formats.\n */\nfunction mapV1MessageToStoredMessage(\n message: StoredMessage | StoredMessageV1\n): StoredMessage {\n // TODO: Remove this mapper when we deprecate the old message format.\n if ((message as StoredMessage).data !== undefined) {\n return message as StoredMessage;\n } else {\n const v1Message = message as StoredMessageV1;\n return {\n type: v1Message.type,\n data: {\n content: v1Message.text,\n role: v1Message.role,\n name: undefined,\n tool_call_id: undefined,\n },\n };\n }\n}\n\nexport function mapStoredMessageToChatMessage(message: StoredMessage) {\n const storedMessage = mapV1MessageToStoredMessage(message);\n switch (storedMessage.type) {\n case \"human\":\n return new HumanMessage(storedMessage.data);\n case \"ai\":\n return new AIMessage(storedMessage.data);\n case \"system\":\n return new SystemMessage(storedMessage.data);\n case \"function\":\n if (storedMessage.data.name === undefined) {\n throw new Error(\"Name must be defined for function messages\");\n }\n return new FunctionMessage(storedMessage.data as FunctionMessageFields);\n case \"tool\":\n if (storedMessage.data.tool_call_id === undefined) {\n throw new Error(\"Tool call ID must be defined for tool messages\");\n }\n return new ToolMessage(storedMessage.data as ToolMessageFields);\n case \"generic\": {\n if (storedMessage.data.role === undefined) {\n throw new Error(\"Role must be defined for chat messages\");\n }\n return new ChatMessage(storedMessage.data as ChatMessageFields);\n }\n default:\n throw new Error(`Got unexpected type: ${storedMessage.type}`);\n }\n}\n\n/**\n * Transforms an array of `StoredMessage` instances into an array of\n * `BaseMessage` instances. It uses the `mapV1MessageToStoredMessage`\n * function to ensure all messages are in the `StoredMessage` format, then\n * creates new instances of the appropriate `BaseMessage` subclass based\n * on the type of each message. This function is used to prepare stored\n * messages for use in a chat context.\n */\nexport function mapStoredMessagesToChatMessages(\n messages: StoredMessage[]\n): BaseMessage[] {\n return messages.map(mapStoredMessageToChatMessage);\n}\n\n/**\n * Transforms an array of `BaseMessage` instances into an array of\n * `StoredMessage` instances. It does this by calling the `toDict` method\n * on each `BaseMessage`, which returns a `StoredMessage`. This function\n * is used to prepare chat messages for storage.\n */\nexport function mapChatMessagesToStoredMessages(\n messages: BaseMessage[]\n): StoredMessage[] {\n return messages.map((message) => message.toDict());\n}\n\nexport function convertToChunk(message: BaseMessage) {\n const type = message._getType();\n if (type === \"human\") {\n return new HumanMessageChunk({ ...message });\n } else if (type === \"ai\") {\n let aiChunkFields: AIMessageChunkFields = {\n ...message,\n };\n if (\"tool_calls\" in aiChunkFields) {\n aiChunkFields = {\n ...aiChunkFields,\n tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({\n ...tc,\n type: \"tool_call_chunk\",\n index: undefined,\n args: JSON.stringify(tc.args),\n })),\n };\n }\n return new AIMessageChunk({ ...aiChunkFields });\n } else if (type === \"system\") {\n return new SystemMessageChunk({ ...message });\n } else if (type === \"function\") {\n return new FunctionMessageChunk({ ...message });\n } else if (ChatMessage.isInstance(message)) {\n return new ChatMessageChunk({ ...message });\n } else {\n throw new Error(\"Unknown message type.\");\n }\n}\n\n/**\n * Collapses an array of tool call chunks into complete tool calls.\n *\n * This function groups tool call chunks by their id and/or index, then attempts to\n * parse and validate the accumulated arguments for each group. Successfully parsed\n * tool calls are returned as valid `ToolCall` objects, while malformed ones are\n * returned as `InvalidToolCall` objects.\n *\n * @param chunks - An array of `ToolCallChunk` objects to collapse\n * @returns An object containing:\n * - `tool_call_chunks`: The original input chunks\n * - `tool_calls`: An array of successfully parsed and validated tool calls\n * - `invalid_tool_calls`: An array of tool calls that failed parsing or validation\n *\n * @remarks\n * Chunks are grouped using the following matching logic:\n * - If a chunk has both an id and index, it matches chunks with the same id and index\n * - If a chunk has only an id, it matches chunks with the same id\n * - If a chunk has only an index, it matches chunks with the same index\n *\n * For each group, the function:\n * 1. Concatenates all `args` strings from the chunks\n * 2. Attempts to parse the concatenated string as JSON\n * 3. Validates that the result is a non-null object with a valid id\n * 4. Creates either a `ToolCall` (if valid) or `InvalidToolCall` (if invalid)\n */\nexport function collapseToolCallChunks(chunks: ToolCallChunk[]): {\n tool_call_chunks: ToolCallChunk[];\n tool_calls: ToolCall[];\n invalid_tool_calls: InvalidToolCall[];\n} {\n const groupedToolCallChunks = chunks.reduce((acc, chunk) => {\n const matchedChunkIndex = acc.findIndex(([match]) => {\n // If chunk has an id and index, match if both are present\n if (\n \"id\" in chunk &&\n chunk.id &&\n \"index\" in chunk &&\n chunk.index !== undefined\n ) {\n return chunk.id === match.id && chunk.index === match.index;\n }\n // If chunk has an id, we match on id\n if (\"id\" in chunk && chunk.id) {\n return chunk.id === match.id;\n }\n // If chunk has an index, we match on index\n if (\"index\" in chunk && chunk.index !== undefined) {\n return chunk.index === match.index;\n }\n return false;\n });\n if (matchedChunkIndex !== -1) {\n acc[matchedChunkIndex].push(chunk);\n } else {\n acc.push([chunk]);\n }\n return acc;\n }, [] as ToolCallChunk[][]);\n\n const toolCalls: ToolCall[] = [];\n const invalidToolCalls: InvalidToolCall[] = [];\n for (const chunks of groupedToolCallChunks) {\n let parsedArgs: Record<string, unknown> | null = null;\n const name = chunks[0]?.name ?? \"\";\n const joinedArgs = chunks\n .map((c) => c.args || \"\")\n .join(\"\")\n .trim();\n const argsStr = joinedArgs.length ? joinedArgs : \"{}\";\n const id = chunks[0]?.id;\n try {\n parsedArgs = parsePartialJson(argsStr);\n if (\n !id ||\n parsedArgs === null ||\n typeof parsedArgs !== \"object\" ||\n Array.isArray(parsedArgs)\n ) {\n throw new Error(\"Malformed tool call chunk args.\");\n }\n toolCalls.push({\n name,\n args: parsedArgs,\n id,\n type: \"tool_call\",\n });\n } catch {\n invalidToolCalls.push({\n name,\n args: argsStr,\n id,\n error: \"Malformed args.\",\n type: \"invalid_tool_call\",\n });\n }\n }\n return {\n tool_call_chunks: chunks,\n tool_calls: toolCalls,\n invalid_tool_calls: invalidToolCalls,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;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M,GACzB,QAAO,MAAM,OAAO,MAAM;AAG5B,OAAI,WAAW,SAAS,MAAM,UAAU,OACtC,QAAO,MAAM,UAAU,MAAM;AAE/B,UAAO;EACR,EAAC;AACF,MAAI,sBAAsB,IACxB,IAAI,mBAAmB,KAAK,MAAM;OAElC,IAAI,KAAK,CAAC,KAAM,EAAC;AAEnB,SAAO;CACR,GAAE,CAAE,EAAsB;CAE3B,MAAMC,YAAwB,CAAE;CAChC,MAAMC,mBAAsC,CAAE;AAC9C,MAAK,MAAMC,YAAU,uBAAuB;EAC1C,IAAIC,aAA6C;EACjD,MAAM,OAAOD,SAAO,IAAI,QAAQ;EAChC,MAAM,aAAaA,SAChB,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,CACxB,KAAK,GAAG,CACR,MAAM;EACT,MAAM,UAAU,WAAW,SAAS,aAAa;EACjD,MAAM,KAAKA,SAAO,IAAI;AACtB,MAAI;GACF,aAAaE,8BAAiB,QAAQ;AACtC,OACE,CAAC,MACD,eAAe,QACf,OAAO,eAAe,YACtB,MAAM,QAAQ,WAAW,CAEzB,OAAM,IAAI,MAAM;GAElB,UAAU,KAAK;IACb;IACA,MAAM;IACN;IACA,MAAM;GACP,EAAC;EACH,QAAO;GACN,iBAAiB,KAAK;IACpB;IACA,MAAM;IACN;IACA,OAAO;IACP,MAAM;GACP,EAAC;EACH;CACF;AACD,QAAO;EACL,kBAAkB;EAClB,YAAY;EACZ,oBAAoB;CACrB;AACF"}
|
|
1
|
+
{"version":3,"file":"utils.cjs","names":["fn: () => T","toolCall: ToolCall | Record<string, unknown>","_isToolCall","x: unknown","params:\n | (BaseMessageFields & { type: string } & Record<string, unknown>)\n | SerializedConstructor","type: string","rest: BaseMessageFields & Record<string, unknown>","HumanMessage","AIMessage","SystemMessage","ToolMessage","RemoveMessage","addLangChainErrorFields","messageLike: BaseMessageLike","isBaseMessage","_isMessageFieldWithRole","messages: BaseMessage[]","string_messages: string[]","role: string","message: StoredMessage | StoredMessageV1","message: StoredMessage","FunctionMessage","ChatMessage","messages: StoredMessage[]","message: BaseMessage","HumanMessageChunk","aiChunkFields: AIMessageChunkFields","AIMessageChunk","SystemMessageChunk","FunctionMessageChunk","ChatMessageChunk","chunks: ToolCallChunk[]","toolCalls: ToolCall[]","invalidToolCalls: InvalidToolCall[]","chunks","parsedArgs: Record<string, unknown> | null","parsePartialJson"],"sources":["../../src/messages/utils.ts"],"sourcesContent":["import { addLangChainErrorFields } from \"../errors/index.js\";\nimport { SerializedConstructor } from \"../load/serializable.js\";\nimport { _isToolCall } from \"../tools/utils.js\";\nimport { parsePartialJson } from \"../utils/json.js\";\nimport { AIMessage, AIMessageChunk, AIMessageChunkFields } from \"./ai.js\";\nimport {\n BaseMessageLike,\n BaseMessage,\n isBaseMessage,\n StoredMessage,\n StoredMessageV1,\n BaseMessageFields,\n _isMessageFieldWithRole,\n} from \"./base.js\";\nimport { ChatMessage, ChatMessageFields, ChatMessageChunk } from \"./chat.js\";\nimport {\n FunctionMessage,\n FunctionMessageChunk,\n FunctionMessageFields,\n} from \"./function.js\";\nimport { HumanMessage, HumanMessageChunk } from \"./human.js\";\nimport { RemoveMessage } from \"./modifier.js\";\nimport { SystemMessage, SystemMessageChunk } from \"./system.js\";\nimport {\n InvalidToolCall,\n ToolCall,\n ToolCallChunk,\n ToolMessage,\n ToolMessageFields,\n} from \"./tool.js\";\n\nexport type $Expand<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;\n\n/**\n * Extracts the explicitly declared keys from a type T.\n *\n * @template T - The type to extract keys from\n * @returns A union of keys that are not string, number, or symbol\n */\ntype $KnownKeys<T> = {\n [K in keyof T]: string extends K\n ? never\n : number extends K\n ? never\n : symbol extends K\n ? never\n : K;\n}[keyof T];\n\n/**\n * Detects if T has an index signature.\n *\n * @template T - The type to check for index signatures\n * @returns True if T has an index signature, false otherwise\n */\ntype $HasIndexSignature<T> = string extends keyof T\n ? true\n : number extends keyof T\n ? true\n : symbol extends keyof T\n ? true\n : false;\n\n/**\n * Detects if T has an index signature and no known keys.\n *\n * @template T - The type to check for index signatures and no known keys\n * @returns True if T has an index signature and no known keys, false otherwise\n */\ntype $OnlyIndexSignatures<T> =\n $HasIndexSignature<T> extends true\n ? [$KnownKeys<T>] extends [never]\n ? true\n : false\n : false;\n\n/**\n * Recursively merges two object types T and U, with U taking precedence over T.\n *\n * This utility type performs a deep merge of two object types:\n * - For keys that exist in both T and U:\n * - If both values are objects (Record<string, unknown>), recursively merge them\n * - Otherwise, U's value takes precedence\n * - For keys that exist only in T, use T's value\n * - For keys that exist only in U, use U's value\n *\n * @template T - The first object type to merge\n * @template U - The second object type to merge (takes precedence over T)\n *\n * @example\n * ```ts\n * type ObjectA = {\n * shared: { a: string; b: number };\n * onlyInA: boolean;\n * };\n *\n * type ObjectB = {\n * shared: { b: string; c: Date };\n * onlyInB: symbol;\n * };\n *\n * type Merged = $MergeObjects<ObjectA, ObjectB>;\n * // Result: {\n * // shared: { a: string; b: string; c: Date };\n * // onlyInA: boolean;\n * // onlyInB: symbol;\n * // }\n * ```\n */\nexport type $MergeObjects<T, U> =\n // If U is purely index-signature based, prefer U as a whole\n $OnlyIndexSignatures<U> extends true\n ? U\n : // If T is purely index-signature based, prefer U as a whole (prevents leaking broad index signatures)\n $OnlyIndexSignatures<T> extends true\n ? U\n : {\n [K in keyof T | keyof U]: K extends keyof T\n ? K extends keyof U\n ? T[K] extends Record<string, unknown>\n ? U[K] extends Record<string, unknown>\n ? $MergeObjects<T[K], U[K]>\n : U[K]\n : U[K]\n : T[K]\n : K extends keyof U\n ? U[K]\n : never;\n };\n\n/**\n * Merges two discriminated unions A and B based on a discriminator key (defaults to \"type\").\n * For each possible value of the discriminator across both unions:\n * - If B has a member with that discriminator value, use B's member\n * - Otherwise use A's member with that discriminator value\n * This effectively merges the unions while giving B's members precedence over A's members.\n *\n * @template A - First discriminated union type that extends Record<Key, PropertyKey>\n * @template B - Second discriminated union type that extends Record<Key, PropertyKey>\n * @template Key - The discriminator key property, defaults to \"type\"\n */\nexport type $MergeDiscriminatedUnion<\n A extends Record<Key, PropertyKey>,\n B extends Record<Key, PropertyKey>,\n Key extends PropertyKey = \"type\",\n> = {\n // Create a mapped type over all possible discriminator values from both A and B\n [T in A[Key] | B[Key]]: [Extract<B, Record<Key, T>>] extends [never] // Check if B has a member with this discriminator value\n ? // If B doesn't have this discriminator value, use A's member\n Extract<A, Record<Key, T>>\n : // If B does have this discriminator value, merge A's and B's members (B takes precedence)\n [Extract<A, Record<Key, T>>] extends [never]\n ? Extract<B, Record<Key, T>>\n : $MergeObjects<Extract<A, Record<Key, T>>, Extract<B, Record<Key, T>>>;\n // Index into the mapped type with all possible discriminator values\n // This converts the mapped type back into a union\n}[A[Key] | B[Key]];\n\nexport type Constructor<T> = new (...args: unknown[]) => T;\n\n/**\n * Immediately-invoked function expression.\n *\n * @param fn - The function to execute\n * @returns The result of the function\n */\nexport const iife = <T>(fn: () => T) => fn();\n\nfunction _coerceToolCall(\n toolCall: ToolCall | Record<string, unknown>\n): ToolCall {\n if (_isToolCall(toolCall)) {\n return toolCall;\n } else if (\n typeof toolCall.id === \"string\" &&\n toolCall.type === \"function\" &&\n typeof toolCall.function === \"object\" &&\n toolCall.function !== null &&\n \"arguments\" in toolCall.function &&\n typeof toolCall.function.arguments === \"string\" &&\n \"name\" in toolCall.function &&\n typeof toolCall.function.name === \"string\"\n ) {\n // Handle OpenAI tool call format\n return {\n id: toolCall.id,\n args: JSON.parse(toolCall.function.arguments),\n name: toolCall.function.name,\n type: \"tool_call\",\n };\n } else {\n // TODO: Throw an error?\n return toolCall as unknown as ToolCall;\n }\n}\n\nfunction isSerializedConstructor(x: unknown): x is SerializedConstructor {\n return (\n typeof x === \"object\" &&\n x != null &&\n (x as SerializedConstructor).lc === 1 &&\n Array.isArray((x as SerializedConstructor).id) &&\n (x as SerializedConstructor).kwargs != null &&\n typeof (x as SerializedConstructor).kwargs === \"object\"\n );\n}\n\nfunction _constructMessageFromParams(\n params:\n | (BaseMessageFields & { type: string } & Record<string, unknown>)\n | SerializedConstructor\n) {\n let type: string;\n let rest: BaseMessageFields & Record<string, unknown>;\n // Support serialized messages\n if (isSerializedConstructor(params)) {\n const className = params.id.at(-1);\n if (className === \"HumanMessage\" || className === \"HumanMessageChunk\") {\n type = \"user\";\n } else if (className === \"AIMessage\" || className === \"AIMessageChunk\") {\n type = \"assistant\";\n } else if (\n className === \"SystemMessage\" ||\n className === \"SystemMessageChunk\"\n ) {\n type = \"system\";\n } else if (\n className === \"FunctionMessage\" ||\n className === \"FunctionMessageChunk\"\n ) {\n type = \"function\";\n } else if (\n className === \"ToolMessage\" ||\n className === \"ToolMessageChunk\"\n ) {\n type = \"tool\";\n } else {\n type = \"unknown\";\n }\n rest = params.kwargs as BaseMessageFields;\n } else {\n const { type: extractedType, ...otherParams } = params;\n type = extractedType;\n rest = otherParams;\n }\n if (type === \"human\" || type === \"user\") {\n return new HumanMessage(rest);\n } else if (type === \"ai\" || type === \"assistant\") {\n const { tool_calls: rawToolCalls, ...other } = rest;\n if (!Array.isArray(rawToolCalls)) {\n return new AIMessage(rest);\n }\n const tool_calls = rawToolCalls.map(_coerceToolCall);\n return new AIMessage({ ...other, tool_calls });\n } else if (type === \"system\") {\n return new SystemMessage(rest);\n } else if (type === \"developer\") {\n return new SystemMessage({\n ...rest,\n additional_kwargs: {\n ...rest.additional_kwargs,\n __openai_role__: \"developer\",\n },\n });\n } else if (type === \"tool\" && \"tool_call_id\" in rest) {\n return new ToolMessage({\n ...rest,\n content: rest.content,\n tool_call_id: rest.tool_call_id as string,\n name: rest.name,\n });\n } else if (type === \"remove\" && \"id\" in rest && typeof rest.id === \"string\") {\n return new RemoveMessage({ ...rest, id: rest.id });\n } else {\n const error = addLangChainErrorFields(\n new Error(\n `Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\\n\\nReceived: ${JSON.stringify(\n params,\n null,\n 2\n )}`\n ),\n \"MESSAGE_COERCION_FAILURE\"\n );\n throw error;\n }\n}\n\nexport function coerceMessageLikeToMessage(\n messageLike: BaseMessageLike\n): BaseMessage {\n if (typeof messageLike === \"string\") {\n return new HumanMessage(messageLike);\n } else if (isBaseMessage(messageLike)) {\n return messageLike;\n }\n if (Array.isArray(messageLike)) {\n const [type, content] = messageLike;\n return _constructMessageFromParams({ type, content });\n } else if (_isMessageFieldWithRole(messageLike)) {\n const { role: type, ...rest } = messageLike;\n return _constructMessageFromParams({ ...rest, type });\n } else {\n return _constructMessageFromParams(messageLike);\n }\n}\n\n/**\n * This function is used by memory classes to get a string representation\n * of the chat message history, based on the message content and role.\n *\n * Produces compact output like:\n * ```\n * Human: What's the weather?\n * AI: Let me check...[tool_calls]\n * Tool: 72°F and sunny\n * ```\n *\n * This avoids token inflation from metadata when stringifying message objects directly.\n */\nexport function getBufferString(\n messages: BaseMessage[],\n humanPrefix = \"Human\",\n aiPrefix = \"AI\"\n): string {\n const string_messages: string[] = [];\n for (const m of messages) {\n let role: string;\n if (m.type === \"human\") {\n role = humanPrefix;\n } else if (m.type === \"ai\") {\n role = aiPrefix;\n } else if (m.type === \"system\") {\n role = \"System\";\n } else if (m.type === \"tool\") {\n role = \"Tool\";\n } else if (m.type === \"generic\") {\n role = (m as ChatMessage).role;\n } else {\n throw new Error(`Got unsupported message type: ${m.type}`);\n }\n const nameStr = m.name ? `${m.name}, ` : \"\";\n\n // Use m.text property which extracts only text content, avoiding metadata\n // For non-string content (e.g., content blocks), m.text extracts only text blocks\n const readableContent = m.text;\n\n let message = `${role}: ${nameStr}${readableContent}`;\n\n // Include tool calls for AI messages (matching Python's get_buffer_string behavior)\n if (m.type === \"ai\") {\n const aiMessage = m as AIMessage;\n if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) {\n message += JSON.stringify(aiMessage.tool_calls);\n } else if (\n aiMessage.additional_kwargs &&\n \"function_call\" in aiMessage.additional_kwargs\n ) {\n // Legacy behavior assumes only one function call per message\n message += JSON.stringify(aiMessage.additional_kwargs.function_call);\n }\n }\n\n string_messages.push(message);\n }\n return string_messages.join(\"\\n\");\n}\n\n/**\n * Maps messages from an older format (V1) to the current `StoredMessage`\n * format. If the message is already in the `StoredMessage` format, it is\n * returned as is. Otherwise, it transforms the V1 message into a\n * `StoredMessage`. This function is important for maintaining\n * compatibility with older message formats.\n */\nfunction mapV1MessageToStoredMessage(\n message: StoredMessage | StoredMessageV1\n): StoredMessage {\n // TODO: Remove this mapper when we deprecate the old message format.\n if ((message as StoredMessage).data !== undefined) {\n return message as StoredMessage;\n } else {\n const v1Message = message as StoredMessageV1;\n return {\n type: v1Message.type,\n data: {\n content: v1Message.text,\n role: v1Message.role,\n name: undefined,\n tool_call_id: undefined,\n },\n };\n }\n}\n\nexport function mapStoredMessageToChatMessage(message: StoredMessage) {\n const storedMessage = mapV1MessageToStoredMessage(message);\n switch (storedMessage.type) {\n case \"human\":\n return new HumanMessage(storedMessage.data);\n case \"ai\":\n return new AIMessage(storedMessage.data);\n case \"system\":\n return new SystemMessage(storedMessage.data);\n case \"function\":\n if (storedMessage.data.name === undefined) {\n throw new Error(\"Name must be defined for function messages\");\n }\n return new FunctionMessage(storedMessage.data as FunctionMessageFields);\n case \"tool\":\n if (storedMessage.data.tool_call_id === undefined) {\n throw new Error(\"Tool call ID must be defined for tool messages\");\n }\n return new ToolMessage(storedMessage.data as ToolMessageFields);\n case \"generic\": {\n if (storedMessage.data.role === undefined) {\n throw new Error(\"Role must be defined for chat messages\");\n }\n return new ChatMessage(storedMessage.data as ChatMessageFields);\n }\n default:\n throw new Error(`Got unexpected type: ${storedMessage.type}`);\n }\n}\n\n/**\n * Transforms an array of `StoredMessage` instances into an array of\n * `BaseMessage` instances. It uses the `mapV1MessageToStoredMessage`\n * function to ensure all messages are in the `StoredMessage` format, then\n * creates new instances of the appropriate `BaseMessage` subclass based\n * on the type of each message. This function is used to prepare stored\n * messages for use in a chat context.\n */\nexport function mapStoredMessagesToChatMessages(\n messages: StoredMessage[]\n): BaseMessage[] {\n return messages.map(mapStoredMessageToChatMessage);\n}\n\n/**\n * Transforms an array of `BaseMessage` instances into an array of\n * `StoredMessage` instances. It does this by calling the `toDict` method\n * on each `BaseMessage`, which returns a `StoredMessage`. This function\n * is used to prepare chat messages for storage.\n */\nexport function mapChatMessagesToStoredMessages(\n messages: BaseMessage[]\n): StoredMessage[] {\n return messages.map((message) => message.toDict());\n}\n\nexport function convertToChunk(message: BaseMessage) {\n const type = message._getType();\n if (type === \"human\") {\n return new HumanMessageChunk({ ...message });\n } else if (type === \"ai\") {\n let aiChunkFields: AIMessageChunkFields = {\n ...message,\n };\n if (\"tool_calls\" in aiChunkFields) {\n aiChunkFields = {\n ...aiChunkFields,\n tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({\n ...tc,\n type: \"tool_call_chunk\",\n index: undefined,\n args: JSON.stringify(tc.args),\n })),\n };\n }\n return new AIMessageChunk({ ...aiChunkFields });\n } else if (type === \"system\") {\n return new SystemMessageChunk({ ...message });\n } else if (type === \"function\") {\n return new FunctionMessageChunk({ ...message });\n } else if (ChatMessage.isInstance(message)) {\n return new ChatMessageChunk({ ...message });\n } else {\n throw new Error(\"Unknown message type.\");\n }\n}\n\n/**\n * Collapses an array of tool call chunks into complete tool calls.\n *\n * This function groups tool call chunks by their id and/or index, then attempts to\n * parse and validate the accumulated arguments for each group. Successfully parsed\n * tool calls are returned as valid `ToolCall` objects, while malformed ones are\n * returned as `InvalidToolCall` objects.\n *\n * @param chunks - An array of `ToolCallChunk` objects to collapse\n * @returns An object containing:\n * - `tool_call_chunks`: The original input chunks\n * - `tool_calls`: An array of successfully parsed and validated tool calls\n * - `invalid_tool_calls`: An array of tool calls that failed parsing or validation\n *\n * @remarks\n * Chunks are grouped using the following matching logic:\n * - If a chunk has both an id and index, it matches chunks with the same id and index\n * - If a chunk has only an id, it matches chunks with the same id\n * - If a chunk has only an index, it matches chunks with the same index\n *\n * For each group, the function:\n * 1. Concatenates all `args` strings from the chunks\n * 2. Attempts to parse the concatenated string as JSON\n * 3. Validates that the result is a non-null object with a valid id\n * 4. Creates either a `ToolCall` (if valid) or `InvalidToolCall` (if invalid)\n */\nexport function collapseToolCallChunks(chunks: ToolCallChunk[]): {\n tool_call_chunks: ToolCallChunk[];\n tool_calls: ToolCall[];\n invalid_tool_calls: InvalidToolCall[];\n} {\n const groupedToolCallChunks = chunks.reduce((acc, chunk) => {\n const matchedChunkIndex = acc.findIndex(([match]) => {\n // If chunk has an id and index, match if both are present\n if (\n \"id\" in chunk &&\n chunk.id &&\n \"index\" in chunk &&\n chunk.index !== undefined\n ) {\n return chunk.id === match.id && chunk.index === match.index;\n }\n // If chunk has an id, we match on id\n if (\"id\" in chunk && chunk.id) {\n return chunk.id === match.id;\n }\n // If chunk has an index, we match on index\n if (\"index\" in chunk && chunk.index !== undefined) {\n return chunk.index === match.index;\n }\n return false;\n });\n if (matchedChunkIndex !== -1) {\n acc[matchedChunkIndex].push(chunk);\n } else {\n acc.push([chunk]);\n }\n return acc;\n }, [] as ToolCallChunk[][]);\n\n const toolCalls: ToolCall[] = [];\n const invalidToolCalls: InvalidToolCall[] = [];\n for (const chunks of groupedToolCallChunks) {\n let parsedArgs: Record<string, unknown> | null = null;\n const name = chunks[0]?.name ?? \"\";\n const joinedArgs = chunks\n .map((c) => c.args || \"\")\n .join(\"\")\n .trim();\n const argsStr = joinedArgs.length ? joinedArgs : \"{}\";\n const id = chunks[0]?.id;\n try {\n parsedArgs = parsePartialJson(argsStr);\n if (\n !id ||\n parsedArgs === null ||\n typeof parsedArgs !== \"object\" ||\n Array.isArray(parsedArgs)\n ) {\n throw new Error(\"Malformed tool call chunk args.\");\n }\n toolCalls.push({\n name,\n args: parsedArgs,\n id,\n type: \"tool_call\",\n });\n } catch {\n invalidToolCalls.push({\n name,\n args: argsStr,\n id,\n error: \"Malformed args.\",\n type: \"invalid_tool_call\",\n });\n }\n }\n return {\n tool_call_chunks: chunks,\n tool_calls: toolCalls,\n invalid_tool_calls: invalidToolCalls,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA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zB,QAAO,MAAM,OAAO,MAAM;AAG5B,OAAI,WAAW,SAAS,MAAM,UAAU,OACtC,QAAO,MAAM,UAAU,MAAM;AAE/B,UAAO;EACR,EAAC;AACF,MAAI,sBAAsB,IACxB,IAAI,mBAAmB,KAAK,MAAM;OAElC,IAAI,KAAK,CAAC,KAAM,EAAC;AAEnB,SAAO;CACR,GAAE,CAAE,EAAsB;CAE3B,MAAMC,YAAwB,CAAE;CAChC,MAAMC,mBAAsC,CAAE;AAC9C,MAAK,MAAMC,YAAU,uBAAuB;EAC1C,IAAIC,aAA6C;EACjD,MAAM,OAAOD,SAAO,IAAI,QAAQ;EAChC,MAAM,aAAaA,SAChB,IAAI,CAAC,MAAM,EAAE,QAAQ,GAAG,CACxB,KAAK,GAAG,CACR,MAAM;EACT,MAAM,UAAU,WAAW,SAAS,aAAa;EACjD,MAAM,KAAKA,SAAO,IAAI;AACtB,MAAI;GACF,aAAaE,8BAAiB,QAAQ;AACtC,OACE,CAAC,MACD,eAAe,QACf,OAAO,eAAe,YACtB,MAAM,QAAQ,WAAW,CAEzB,OAAM,IAAI,MAAM;GAElB,UAAU,KAAK;IACb;IACA,MAAM;IACN;IACA,MAAM;GACP,EAAC;EACH,QAAO;GACN,iBAAiB,KAAK;IACpB;IACA,MAAM;IACN;IACA,OAAO;IACP,MAAM;GACP,EAAC;EACH;CACF;AACD,QAAO;EACL,kBAAkB;EAClB,YAAY;EACZ,oBAAoB;CACrB;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_errors_index = require('../errors/index.cjs');
|
|
2
2
|
const require_base = require('../runnables/base.cjs');
|
|
3
3
|
require('../runnables/index.cjs');
|
|
4
4
|
|
|
@@ -97,7 +97,7 @@ var OutputParserException = class extends Error {
|
|
|
97
97
|
if (sendToLLM) {
|
|
98
98
|
if (observation === void 0 || llmOutput === void 0) throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");
|
|
99
99
|
}
|
|
100
|
-
|
|
100
|
+
require_errors_index.addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE");
|
|
101
101
|
}
|
|
102
102
|
};
|
|
103
103
|
|