@langchain/core 1.1.7 → 1.1.8

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/caches/index.d.cts.map +1 -1
  3. package/dist/callbacks/base.d.cts.map +1 -1
  4. package/dist/language_models/chat_models.d.ts.map +1 -1
  5. package/dist/load/index.cjs +85 -25
  6. package/dist/load/index.cjs.map +1 -1
  7. package/dist/load/index.d.cts +113 -3
  8. package/dist/load/index.d.cts.map +1 -1
  9. package/dist/load/index.d.ts +113 -3
  10. package/dist/load/index.d.ts.map +1 -1
  11. package/dist/load/index.js +85 -25
  12. package/dist/load/index.js.map +1 -1
  13. package/dist/load/serializable.cjs +6 -1
  14. package/dist/load/serializable.cjs.map +1 -1
  15. package/dist/load/serializable.d.cts +15 -1
  16. package/dist/load/serializable.d.cts.map +1 -1
  17. package/dist/load/serializable.d.ts +15 -1
  18. package/dist/load/serializable.d.ts.map +1 -1
  19. package/dist/load/serializable.js +6 -1
  20. package/dist/load/serializable.js.map +1 -1
  21. package/dist/load/validation.cjs +98 -0
  22. package/dist/load/validation.cjs.map +1 -0
  23. package/dist/load/validation.js +95 -0
  24. package/dist/load/validation.js.map +1 -0
  25. package/dist/messages/base.cjs +1 -0
  26. package/dist/messages/base.cjs.map +1 -1
  27. package/dist/messages/base.d.cts +2 -3
  28. package/dist/messages/base.d.cts.map +1 -1
  29. package/dist/messages/base.d.ts +2 -3
  30. package/dist/messages/base.d.ts.map +1 -1
  31. package/dist/messages/base.js +1 -0
  32. package/dist/messages/base.js.map +1 -1
  33. package/dist/messages/message.cjs.map +1 -1
  34. package/dist/messages/message.d.cts +34 -1
  35. package/dist/messages/message.d.cts.map +1 -1
  36. package/dist/messages/message.d.ts +34 -1
  37. package/dist/messages/message.d.ts.map +1 -1
  38. package/dist/messages/message.js.map +1 -1
  39. package/dist/messages/tool.d.ts.map +1 -1
  40. package/dist/utils/event_source_parse.d.cts.map +1 -1
  41. package/dist/utils/stream.d.cts.map +1 -1
  42. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @langchain/core
2
2
 
3
+ ## 1.1.8
4
+
5
+ ### Patch Changes
6
+
7
+ - [#9707](https://github.com/langchain-ai/langchainjs/pull/9707) [`e5063f9`](https://github.com/langchain-ai/langchainjs/commit/e5063f9c6e9989ea067dfdff39262b9e7b6aba62) Thanks [@hntrl](https://github.com/hntrl)! - add security hardening for `load`
8
+
9
+ - [#9684](https://github.com/langchain-ai/langchainjs/pull/9684) [`8996647`](https://github.com/langchain-ai/langchainjs/commit/89966470e8c0b112ce4f9a326004af6a4173f9e6) Thanks [@christian-bromann](https://github.com/christian-bromann)! - fix(core): document purpose of name in base message
10
+
3
11
  ## 1.1.7
4
12
 
5
13
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":["___messages_ai_js0","___messages_chat_js0","___messages_function_js0","___messages_human_js0","___messages_system_js0","___messages_tool_js0","HashKeyEncoder","Generation","StoredGeneration","defaultHashKeyEncoder","deserializeStoredGeneration","___messages_message_js1","MessageStructure","AIMessage","ChatMessage","FunctionMessage","HumanMessage","SystemMessage","ToolMessage","serializeGeneration","BaseCache","T","Promise","InMemoryCache","Map"],"sources":["../../src/caches/index.d.ts"],"sourcesContent":["import { type HashKeyEncoder } from \"../utils/hash.js\";\nimport type { Generation } from \"../outputs.js\";\nimport { type StoredGeneration } from \"../messages/base.js\";\nexport declare const defaultHashKeyEncoder: HashKeyEncoder;\nexport declare function deserializeStoredGeneration(storedGeneration: StoredGeneration): {\n text: string;\n message: import(\"../messages/ai.js\").AIMessage<import(\"../messages/message.js\").MessageStructure> | import(\"../messages/chat.js\").ChatMessage<import(\"../messages/message.js\").MessageStructure> | import(\"../messages/function.js\").FunctionMessage<import(\"../messages/message.js\").MessageStructure> | import(\"../messages/human.js\").HumanMessage<import(\"../messages/message.js\").MessageStructure> | import(\"../messages/system.js\").SystemMessage<import(\"../messages/message.js\").MessageStructure> | import(\"../messages/tool.js\").ToolMessage<import(\"../messages/message.js\").MessageStructure>;\n} | {\n message?: undefined;\n text: string;\n};\nexport declare function serializeGeneration(generation: Generation): StoredGeneration;\n/**\n * Base class for all caches. All caches should extend this class.\n */\nexport declare abstract class BaseCache<T = Generation[]> {\n protected keyEncoder: HashKeyEncoder;\n /**\n * Sets a custom key encoder function for the cache.\n * This function should take a prompt and an LLM key and return a string\n * that will be used as the cache key.\n * @param keyEncoderFn The custom key encoder function.\n */\n makeDefaultKeyEncoder(keyEncoderFn: HashKeyEncoder): void;\n abstract lookup(prompt: string, llmKey: string): Promise<T | null>;\n abstract update(prompt: string, llmKey: string, value: T): Promise<void>;\n}\n/**\n * A cache for storing LLM generations that stores data in memory.\n */\nexport declare class InMemoryCache<T = Generation[]> extends BaseCache<T> {\n private cache;\n constructor(map?: Map<string, T>);\n /**\n * Retrieves data from the cache using a prompt and an LLM key. If the\n * data is not found, it returns null.\n * @param prompt The prompt used to find the data.\n * @param llmKey The LLM key used to find the data.\n * @returns The data corresponding to the prompt and LLM key, or null if not found.\n */\n lookup(prompt: string, llmKey: string): Promise<T | null>;\n /**\n * Updates the cache with new data using a prompt and an LLM key.\n * @param prompt The prompt used to store the data.\n * @param llmKey The LLM key used to store the data.\n * @param value The data to be stored.\n */\n update(prompt: string, llmKey: string, value: T): Promise<void>;\n /**\n * Returns a global instance of InMemoryCache using a predefined global\n * map as the initial cache.\n * @returns A global instance of InMemoryCache.\n */\n static global(): InMemoryCache;\n}\n//# sourceMappingURL=index.d.ts.map"],"mappings":";;;;;;;;;;;;cAGqBS,uBAAuBH;iBACpBI,2BAAAA,mBAA8CF;;;;;;;iBAO9CW,mBAAAA,aAAgCZ,aAAaC;AARrE;AACA;;uBAW8BY,cAAcb;wBAClBD;;;;;;;sCAOcA;mDACagB,QAAQD;yDACFA,IAAIC;;AAnB4d;AAK3hB;AAIA;AAA4Cf,cAevBgB,aAfuBhB,CAAAA,IAeLA,UAfKA,EAAAA,CAAAA,SAeiBa,SAfjBb,CAe2Bc,CAf3Bd,CAAAA,CAAAA;EAClBD,QAAAA,KAAAA;EAOcA,WAAAA,CAAAA,GAAAA,CAAAA,EASlBkB,GATkBlB,CAAAA,MAAAA,EASNe,CATMf,CAAAA;EACqBe;;;;AACS;AAKtE;;EAAuEA,MAAAA,CAAAA,MAAAA,EAAAA,MAAAA,EAAAA,MAAAA,EAAAA,MAAAA,CAAAA,EAU3BC,OAV2BD,CAUnBA,CAVmBA,GAAAA,IAAAA,CAAAA;EAErCA;;;;;;EAqBbE,MAAAA,CAAAA,MAAAA,EAAAA,MAAAA,EAAAA,MAAAA,EAAAA,MAAAA,EAAAA,KAAAA,EAN6BF,CAM7BE,CAAAA,EANiCD,OAMjCC,CAAAA,IAAAA,CAAAA;EAvBwCH;AAAS;;;;mBAuBjDG"}
1
+ {"version":3,"file":"index.d.cts","names":["___messages_ai_js0","___messages_chat_js0","___messages_function_js0","___messages_human_js0","___messages_system_js0","___messages_tool_js0","HashKeyEncoder","Generation","StoredGeneration","defaultHashKeyEncoder","deserializeStoredGeneration","___messages_message_js0","MessageStructure","AIMessage","ChatMessage","FunctionMessage","HumanMessage","SystemMessage","ToolMessage","serializeGeneration","BaseCache","T","Promise","InMemoryCache","Map"],"sources":["../../src/caches/index.d.ts"],"sourcesContent":["import { type HashKeyEncoder } from \"../utils/hash.js\";\nimport type { Generation } from \"../outputs.js\";\nimport { type StoredGeneration } from \"../messages/base.js\";\nexport declare const defaultHashKeyEncoder: HashKeyEncoder;\nexport declare function deserializeStoredGeneration(storedGeneration: StoredGeneration): {\n text: string;\n message: import(\"../messages/ai.js\").AIMessage<import(\"../messages/message.js\").MessageStructure> | import(\"../messages/chat.js\").ChatMessage<import(\"../messages/message.js\").MessageStructure> | import(\"../messages/function.js\").FunctionMessage<import(\"../messages/message.js\").MessageStructure> | import(\"../messages/human.js\").HumanMessage<import(\"../messages/message.js\").MessageStructure> | import(\"../messages/system.js\").SystemMessage<import(\"../messages/message.js\").MessageStructure> | import(\"../messages/tool.js\").ToolMessage<import(\"../messages/message.js\").MessageStructure>;\n} | {\n message?: undefined;\n text: string;\n};\nexport declare function serializeGeneration(generation: Generation): StoredGeneration;\n/**\n * Base class for all caches. All caches should extend this class.\n */\nexport declare abstract class BaseCache<T = Generation[]> {\n protected keyEncoder: HashKeyEncoder;\n /**\n * Sets a custom key encoder function for the cache.\n * This function should take a prompt and an LLM key and return a string\n * that will be used as the cache key.\n * @param keyEncoderFn The custom key encoder function.\n */\n makeDefaultKeyEncoder(keyEncoderFn: HashKeyEncoder): void;\n abstract lookup(prompt: string, llmKey: string): Promise<T | null>;\n abstract update(prompt: string, llmKey: string, value: T): Promise<void>;\n}\n/**\n * A cache for storing LLM generations that stores data in memory.\n */\nexport declare class InMemoryCache<T = Generation[]> extends BaseCache<T> {\n private cache;\n constructor(map?: Map<string, T>);\n /**\n * Retrieves data from the cache using a prompt and an LLM key. If the\n * data is not found, it returns null.\n * @param prompt The prompt used to find the data.\n * @param llmKey The LLM key used to find the data.\n * @returns The data corresponding to the prompt and LLM key, or null if not found.\n */\n lookup(prompt: string, llmKey: string): Promise<T | null>;\n /**\n * Updates the cache with new data using a prompt and an LLM key.\n * @param prompt The prompt used to store the data.\n * @param llmKey The LLM key used to store the data.\n * @param value The data to be stored.\n */\n update(prompt: string, llmKey: string, value: T): Promise<void>;\n /**\n * Returns a global instance of InMemoryCache using a predefined global\n * map as the initial cache.\n * @returns A global instance of InMemoryCache.\n */\n static global(): InMemoryCache;\n}\n//# sourceMappingURL=index.d.ts.map"],"mappings":";;;;;;;;;;;;cAGqBS,uBAAuBH;iBACpBI,2BAAAA,mBAA8CF;;;;;;;iBAO9CW,mBAAAA,aAAgCZ,aAAaC;AARrE;AACA;;uBAW8BY,cAAcb;wBAClBD;;;;;;;sCAOcA;mDACagB,QAAQD;yDACFA,IAAIC;;AAnB4d;AAK3hB;AAIA;AAA4Cf,cAevBgB,aAfuBhB,CAAAA,IAeLA,UAfKA,EAAAA,CAAAA,SAeiBa,SAfjBb,CAe2Bc,CAf3Bd,CAAAA,CAAAA;EAClBD,QAAAA,KAAAA;EAOcA,WAAAA,CAAAA,GAAAA,CAAAA,EASlBkB,GATkBlB,CAAAA,MAAAA,EASNe,CATMf,CAAAA;EACqBe;;;;AACS;AAKtE;;EAAuEA,MAAAA,CAAAA,MAAAA,EAAAA,MAAAA,EAAAA,MAAAA,EAAAA,MAAAA,CAAAA,EAU3BC,OAV2BD,CAUnBA,CAVmBA,GAAAA,IAAAA,CAAAA;EAErCA;;;;;;EAqBbE,MAAAA,CAAAA,MAAAA,EAAAA,MAAAA,EAAAA,MAAAA,EAAAA,MAAAA,EAAAA,KAAAA,EAN6BF,CAM7BE,CAAAA,EANiCD,OAMjCC,CAAAA,IAAAA,CAAAA;EAvBwCH;AAAS;;;;mBAuBjDG"}
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.cts","names":["ChainValues","BaseMessage","AgentAction","AgentFinish","ChatGenerationChunk","GenerationChunk","LLMResult","Serializable","Serialized","SerializedNotImplemented","SerializedFields","DocumentInterface","Error","BaseCallbackHandlerInput","NewTokenIndices","HandleLLMNewTokenCallbackFields","BaseCallbackHandlerMethodsClass","Record","Promise","CallbackHandlerMethods","CallbackHandlerPrefersStreaming","callbackHandlerPrefersStreaming","BaseCallbackHandler","___messages_message_js0","MessageStructure","MessageType","isBaseCallbackHandler"],"sources":["../../src/callbacks/base.d.ts"],"sourcesContent":["import type { ChainValues } from \"../utils/types/index.js\";\nimport type { BaseMessage } from \"../messages/base.js\";\nimport type { AgentAction, AgentFinish } from \"../agents.js\";\nimport type { ChatGenerationChunk, GenerationChunk, LLMResult } from \"../outputs.js\";\nimport { Serializable, Serialized, SerializedNotImplemented } from \"../load/serializable.js\";\nimport type { SerializedFields } from \"../load/map_keys.js\";\nimport type { DocumentInterface } from \"../documents/document.js\";\ntype Error = any;\n/**\n * Interface for the input parameters of the BaseCallbackHandler class. It\n * allows to specify which types of events should be ignored by the\n * callback handler.\n */\nexport interface BaseCallbackHandlerInput {\n ignoreLLM?: boolean;\n ignoreChain?: boolean;\n ignoreAgent?: boolean;\n ignoreRetriever?: boolean;\n ignoreCustomEvent?: boolean;\n _awaitHandler?: boolean;\n raiseError?: boolean;\n}\n/**\n * Interface for the indices of a new token produced by an LLM or Chat\n * Model in streaming mode.\n */\nexport interface NewTokenIndices {\n prompt: number;\n completion: number;\n}\nexport type HandleLLMNewTokenCallbackFields = {\n chunk?: GenerationChunk | ChatGenerationChunk;\n};\n/**\n * Abstract class that provides a set of optional methods that can be\n * overridden in derived classes to handle various events during the\n * execution of a LangChain application.\n */\ndeclare abstract class BaseCallbackHandlerMethodsClass {\n /**\n * Called at the start of an LLM or Chat Model run, with the prompt(s)\n * and the run ID.\n */\n handleLLMStart?(llm: Serialized, prompts: string[], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>, runName?: string): Promise<any> | any;\n /**\n * Called when an LLM/ChatModel in `streaming` mode produces a new token\n */\n handleLLMNewToken?(token: string, \n /**\n * idx.prompt is the index of the prompt that produced the token\n * (if there are multiple prompts)\n * idx.completion is the index of the completion that produced the token\n * (if multiple completions per prompt are requested)\n */\n idx: NewTokenIndices, runId: string, parentRunId?: string, tags?: string[], fields?: HandleLLMNewTokenCallbackFields): Promise<any> | any;\n /**\n * Called if an LLM/ChatModel run encounters an error\n */\n handleLLMError?(err: Error, runId: string, parentRunId?: string, tags?: string[], extraParams?: Record<string, unknown>): Promise<any> | any;\n /**\n * Called at the end of an LLM/ChatModel run, with the output and the run ID.\n */\n handleLLMEnd?(output: LLMResult, runId: string, parentRunId?: string, tags?: string[], extraParams?: Record<string, unknown>): Promise<any> | any;\n /**\n * Called at the start of a Chat Model run, with the prompt(s)\n * and the run ID.\n */\n handleChatModelStart?(llm: Serialized, messages: BaseMessage[][], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>, runName?: string): Promise<any> | any;\n /**\n * Called at the start of a Chain run, with the chain name and inputs\n * and the run ID.\n */\n handleChainStart?(chain: Serialized, inputs: ChainValues, runId: string, runType?: string, tags?: string[], metadata?: Record<string, unknown>, runName?: string, parentRunId?: string, extra?: Record<string, unknown>): Promise<any> | any;\n /**\n * Called if a Chain run encounters an error\n */\n handleChainError?(err: Error, runId: string, parentRunId?: string, tags?: string[], kwargs?: {\n inputs?: Record<string, unknown>;\n }): Promise<any> | any;\n /**\n * Called at the end of a Chain run, with the outputs and the run ID.\n */\n handleChainEnd?(outputs: ChainValues, runId: string, parentRunId?: string, tags?: string[], kwargs?: {\n inputs?: Record<string, unknown>;\n }): Promise<any> | any;\n /**\n * Called at the start of a Tool run, with the tool name and input\n * and the run ID.\n */\n handleToolStart?(tool: Serialized, input: string, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>, runName?: string): Promise<any> | any;\n /**\n * Called if a Tool run encounters an error\n */\n handleToolError?(err: Error, runId: string, parentRunId?: string, tags?: string[]): Promise<any> | any;\n /**\n * Called at the end of a Tool run, with the tool output and the run ID.\n */\n handleToolEnd?(output: any, runId: string, parentRunId?: string, tags?: string[]): Promise<any> | any;\n handleText?(text: string, runId: string, parentRunId?: string, tags?: string[]): Promise<void> | void;\n /**\n * Called when an agent is about to execute an action,\n * with the action and the run ID.\n */\n handleAgentAction?(action: AgentAction, runId: string, parentRunId?: string, tags?: string[]): Promise<void> | void;\n /**\n * Called when an agent finishes execution, before it exits.\n * with the final output and the run ID.\n */\n handleAgentEnd?(action: AgentFinish, runId: string, parentRunId?: string, tags?: string[]): Promise<void> | void;\n handleRetrieverStart?(retriever: Serialized, query: string, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>, name?: string): Promise<any> | any;\n handleRetrieverEnd?(documents: DocumentInterface[], runId: string, parentRunId?: string, tags?: string[]): Promise<any> | any;\n handleRetrieverError?(err: Error, runId: string, parentRunId?: string, tags?: string[]): Promise<any> | any;\n handleCustomEvent?(eventName: string, data: any, runId: string, tags?: string[], metadata?: Record<string, any>): Promise<any> | any;\n}\n/**\n * Base interface for callbacks. All methods are optional. If a method is not\n * implemented, it will be ignored. If a method is implemented, it will be\n * called at the appropriate time. All methods are called with the run ID of\n * the LLM/ChatModel/Chain that is running, which is generated by the\n * CallbackManager.\n *\n * @interface\n */\nexport type CallbackHandlerMethods = BaseCallbackHandlerMethodsClass;\n/**\n * Interface for handlers that can indicate a preference for streaming responses.\n * When implemented, this allows the handler to signal whether it prefers to receive\n * streaming responses from language models rather than complete responses.\n */\nexport interface CallbackHandlerPrefersStreaming {\n readonly lc_prefer_streaming: boolean;\n}\nexport declare function callbackHandlerPrefersStreaming(x: BaseCallbackHandler): unknown;\n/**\n * Abstract base class for creating callback handlers in the LangChain\n * framework. It provides a set of optional methods that can be overridden\n * in derived classes to handle various events during the execution of a\n * LangChain application.\n */\nexport declare abstract class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass implements BaseCallbackHandlerInput, Serializable {\n lc_serializable: boolean;\n get lc_namespace(): [\"langchain_core\", \"callbacks\", string];\n get lc_secrets(): {\n [key: string]: string;\n } | undefined;\n get lc_attributes(): {\n [key: string]: string;\n } | undefined;\n get lc_aliases(): {\n [key: string]: string;\n } | undefined;\n get lc_serializable_keys(): string[] | undefined;\n /**\n * The name of the serializable. Override to provide an alias or\n * to preserve the serialized module name in minified environments.\n *\n * Implemented as a static method to support loading logic.\n */\n static lc_name(): string;\n /**\n * The final serialized identifier for the module.\n */\n get lc_id(): string[];\n lc_kwargs: SerializedFields;\n abstract name: string;\n ignoreLLM: boolean;\n ignoreChain: boolean;\n ignoreAgent: boolean;\n ignoreRetriever: boolean;\n ignoreCustomEvent: boolean;\n raiseError: boolean;\n awaitHandlers: boolean;\n constructor(input?: BaseCallbackHandlerInput);\n copy(): BaseCallbackHandler;\n toJSON(): Serialized;\n toJSONNotImplemented(): SerializedNotImplemented;\n static fromMethods(methods: CallbackHandlerMethods): {\n name: string;\n /**\n * Called at the start of an LLM or Chat Model run, with the prompt(s)\n * and the run ID.\n */\n handleLLMStart?(llm: Serialized, prompts: string[], runId: string, parentRunId?: string | undefined, extraParams?: Record<string, unknown> | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runName?: string | undefined): any;\n /**\n * Called when an LLM/ChatModel in `streaming` mode produces a new token\n */\n handleLLMNewToken?(token: string, idx: NewTokenIndices, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, fields?: HandleLLMNewTokenCallbackFields | undefined): any;\n /**\n * Called if an LLM/ChatModel run encounters an error\n */\n handleLLMError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, extraParams?: Record<string, unknown> | undefined): any;\n /**\n * Called at the end of an LLM/ChatModel run, with the output and the run ID.\n */\n handleLLMEnd?(output: LLMResult, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, extraParams?: Record<string, unknown> | undefined): any;\n /**\n * Called at the start of a Chat Model run, with the prompt(s)\n * and the run ID.\n */\n handleChatModelStart?(llm: Serialized, messages: BaseMessage<import(\"../messages/message.js\").MessageStructure, import(\"../messages/message.js\").MessageType>[][], runId: string, parentRunId?: string | undefined, extraParams?: Record<string, unknown> | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runName?: string | undefined): any;\n /**\n * Called at the start of a Chain run, with the chain name and inputs\n * and the run ID.\n */\n handleChainStart?(chain: Serialized, inputs: ChainValues, runId: string, runType?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runName?: string | undefined, parentRunId?: string | undefined, extra?: Record<string, unknown> | undefined): any;\n /**\n * Called if a Chain run encounters an error\n */\n handleChainError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, kwargs?: {\n inputs?: Record<string, unknown> | undefined;\n } | undefined): any;\n /**\n * Called at the end of a Chain run, with the outputs and the run ID.\n */\n handleChainEnd?(outputs: ChainValues, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, kwargs?: {\n inputs?: Record<string, unknown> | undefined;\n } | undefined): any;\n /**\n * Called at the start of a Tool run, with the tool name and input\n * and the run ID.\n */\n handleToolStart?(tool: Serialized, input: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runName?: string | undefined): any;\n /**\n * Called if a Tool run encounters an error\n */\n handleToolError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;\n /**\n * Called at the end of a Tool run, with the tool output and the run ID.\n */\n handleToolEnd?(output: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;\n handleText?(text: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): void | Promise<void>;\n /**\n * Called when an agent is about to execute an action,\n * with the action and the run ID.\n */\n handleAgentAction?(action: AgentAction, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): void | Promise<void>;\n /**\n * Called when an agent finishes execution, before it exits.\n * with the final output and the run ID.\n */\n handleAgentEnd?(action: AgentFinish, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): void | Promise<void>;\n handleRetrieverStart?(retriever: Serialized, query: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, name?: string | undefined): any;\n handleRetrieverEnd?(documents: DocumentInterface<Record<string, any>>[], runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;\n handleRetrieverError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;\n handleCustomEvent?(eventName: string, data: any, runId: string, tags?: string[] | undefined, metadata?: Record<string, any> | undefined): any;\n lc_serializable: boolean;\n get lc_namespace(): [\"langchain_core\", \"callbacks\", string];\n get lc_secrets(): {\n [key: string]: string;\n } | undefined;\n get lc_attributes(): {\n [key: string]: string;\n } | undefined;\n get lc_aliases(): {\n [key: string]: string;\n } | undefined;\n get lc_serializable_keys(): string[] | undefined;\n /**\n * The final serialized identifier for the module.\n */\n get lc_id(): string[];\n lc_kwargs: SerializedFields;\n ignoreLLM: boolean;\n ignoreChain: boolean;\n ignoreAgent: boolean;\n ignoreRetriever: boolean;\n ignoreCustomEvent: boolean;\n raiseError: boolean;\n awaitHandlers: boolean;\n copy(): BaseCallbackHandler;\n toJSON(): Serialized;\n toJSONNotImplemented(): SerializedNotImplemented;\n };\n}\nexport declare const isBaseCallbackHandler: (x: unknown) => boolean;\nexport {};\n//# sourceMappingURL=base.d.ts.map"],"mappings":";;;;;;;;;;KAOKY,KAAAA;;;AAD6D;AAOlE;AAaA;AAIYG,UAjBKF,wBAAAA,CAiB0B;EAQpBG,SAAAA,CAAAA,EAAAA,OAAAA;EAKER,WAAAA,CAAAA,EAAAA,OAAAA;EAAkFS,WAAAA,CAAAA,EAAAA,OAAAA;EAAqDA,eAAAA,CAAAA,EAAAA,OAAAA;EAA4CC,iBAAAA,CAAAA,EAAAA,OAAAA;EAWnMJ,aAAAA,CAAAA,EAAAA,OAAAA;EAAgFC,UAAAA,CAAAA,EAAAA,OAAAA;;;;;;AAQgBE,UApCxFH,eAAAA,CAoCwFG;EAA0BC,MAAAA,EAAAA,MAAAA;EAKpGV,UAAAA,EAAAA,MAAAA;;AAA0FS,KArC7GF,+BAAAA,GAqC6GE;EAAqDA,KAAAA,CAAAA,EApClKZ,eAoCkKY,GApChJb,mBAoCgJa;CAA4CC;;;;;;uBA7BnMF,+BAAAA,CAsCIJ;EACVK;;;;EAOTC,cAAAA,CAAAA,CAAAA,GAAAA,EAzCiBV,UAyCjBU,EAAAA,OAAAA,EAAAA,MAAAA,EAAAA,EAAAA,KAAAA,EAAAA,MAAAA,EAAAA,WAAAA,CAAAA,EAAAA,MAAAA,EAAAA,WAAAA,CAAAA,EAzCmGD,MAyCnGC,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA,EAAAA,IAAAA,CAAAA,EAAAA,MAAAA,EAAAA,EAAAA,QAAAA,CAAAA,EAzCwJD,MAyCxJC,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA,EAAAA,OAAAA,CAAAA,EAAAA,M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T,CAAAA,GAAAA,CAAAA,GAAAA,GAAAA;EApI0BO,iBAAAA,CAAAA,CAAAA,SAAAA,EAAAA,MAAAA,EAAAA,IAAAA,EAAAA,GAAAA,EAAAA,KAAAA,EAAAA,MAAAA,EAAAA,IAAAA,CAAAA,EAAAA,MAAAA,EAAAA,EAAAA,QAAAA,CAAAA,EA3BsCC,MA2BtCD,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,CAAAA,EA3B4DE,OA2B5DF,CAAAA,GAAAA,CAAAA,GAAAA,GAAAA;;;AAAiF;AAuI3I;;;;;;;KAvJYG,sBAAAA,GAAyBH;;;;;;UAMpBI,+BAAAA;;;iBAGOC,+BAAAA,IAAmCC;;;;;;;uBAO7BA,mBAAAA,SAA4BN,+BAAAA,YAA2CH,0BAA0BN;;;;;;;;;;;;;;;;;;;;;;;;aAwBhHG;;;;;;;;;sBASSG;UACZS;YACEd;0BACcC;8BACIU;;;;;;yBAMHX,8FAA8FS,6EAA6EA;;;;2CAIzJH,wGAAwGC;;;;0HAIzBE;;;;0BAIhGX,uGAAuGW;;;;;+BAKlGT,sBAAsBP,+GAAiLgB,6EAA6EA;;;;;6BAKtRT,oBAAoBR,kGAAkGiB,6GAA6GA;;;;;eAK/OA;;;;;6BAKYjB;eACZiB;;;;;;2BAMUT,oHAAoHS;;;;;;;;;oHAS3BC;;;;;+BAKrFhB,mGAAmGgB;;;;;4BAKtGf,mGAAmGe;qCAC1FV,oHAAoHS;mCACtHN,kBAAkBM;;4GAEuDA;;;;;;;;;;;;;;;;;eAiB7FP;;;;;;;;YAQHY;cACEd;4BACcC;;;cAGXiB"}
1
+ {"version":3,"file":"base.d.cts","names":["ChainValues","BaseMessage","AgentAction","AgentFinish","ChatGenerationChunk","GenerationChunk","LLMResult","Serializable","Serialized","SerializedNotImplemented","SerializedFields","DocumentInterface","Error","BaseCallbackHandlerInput","NewTokenIndices","HandleLLMNewTokenCallbackFields","BaseCallbackHandlerMethodsClass","Record","Promise","CallbackHandlerMethods","CallbackHandlerPrefersStreaming","callbackHandlerPrefersStreaming","BaseCallbackHandler","___messages_message_js5","MessageStructure","MessageType","isBaseCallbackHandler"],"sources":["../../src/callbacks/base.d.ts"],"sourcesContent":["import type { ChainValues } from \"../utils/types/index.js\";\nimport type { BaseMessage } from \"../messages/base.js\";\nimport type { AgentAction, AgentFinish } from \"../agents.js\";\nimport type { ChatGenerationChunk, GenerationChunk, LLMResult } from \"../outputs.js\";\nimport { Serializable, Serialized, SerializedNotImplemented } from \"../load/serializable.js\";\nimport type { SerializedFields } from \"../load/map_keys.js\";\nimport type { DocumentInterface } from \"../documents/document.js\";\ntype Error = any;\n/**\n * Interface for the input parameters of the BaseCallbackHandler class. It\n * allows to specify which types of events should be ignored by the\n * callback handler.\n */\nexport interface BaseCallbackHandlerInput {\n ignoreLLM?: boolean;\n ignoreChain?: boolean;\n ignoreAgent?: boolean;\n ignoreRetriever?: boolean;\n ignoreCustomEvent?: boolean;\n _awaitHandler?: boolean;\n raiseError?: boolean;\n}\n/**\n * Interface for the indices of a new token produced by an LLM or Chat\n * Model in streaming mode.\n */\nexport interface NewTokenIndices {\n prompt: number;\n completion: number;\n}\nexport type HandleLLMNewTokenCallbackFields = {\n chunk?: GenerationChunk | ChatGenerationChunk;\n};\n/**\n * Abstract class that provides a set of optional methods that can be\n * overridden in derived classes to handle various events during the\n * execution of a LangChain application.\n */\ndeclare abstract class BaseCallbackHandlerMethodsClass {\n /**\n * Called at the start of an LLM or Chat Model run, with the prompt(s)\n * and the run ID.\n */\n handleLLMStart?(llm: Serialized, prompts: string[], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>, runName?: string): Promise<any> | any;\n /**\n * Called when an LLM/ChatModel in `streaming` mode produces a new token\n */\n handleLLMNewToken?(token: string, \n /**\n * idx.prompt is the index of the prompt that produced the token\n * (if there are multiple prompts)\n * idx.completion is the index of the completion that produced the token\n * (if multiple completions per prompt are requested)\n */\n idx: NewTokenIndices, runId: string, parentRunId?: string, tags?: string[], fields?: HandleLLMNewTokenCallbackFields): Promise<any> | any;\n /**\n * Called if an LLM/ChatModel run encounters an error\n */\n handleLLMError?(err: Error, runId: string, parentRunId?: string, tags?: string[], extraParams?: Record<string, unknown>): Promise<any> | any;\n /**\n * Called at the end of an LLM/ChatModel run, with the output and the run ID.\n */\n handleLLMEnd?(output: LLMResult, runId: string, parentRunId?: string, tags?: string[], extraParams?: Record<string, unknown>): Promise<any> | any;\n /**\n * Called at the start of a Chat Model run, with the prompt(s)\n * and the run ID.\n */\n handleChatModelStart?(llm: Serialized, messages: BaseMessage[][], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>, runName?: string): Promise<any> | any;\n /**\n * Called at the start of a Chain run, with the chain name and inputs\n * and the run ID.\n */\n handleChainStart?(chain: Serialized, inputs: ChainValues, runId: string, runType?: string, tags?: string[], metadata?: Record<string, unknown>, runName?: string, parentRunId?: string, extra?: Record<string, unknown>): Promise<any> | any;\n /**\n * Called if a Chain run encounters an error\n */\n handleChainError?(err: Error, runId: string, parentRunId?: string, tags?: string[], kwargs?: {\n inputs?: Record<string, unknown>;\n }): Promise<any> | any;\n /**\n * Called at the end of a Chain run, with the outputs and the run ID.\n */\n handleChainEnd?(outputs: ChainValues, runId: string, parentRunId?: string, tags?: string[], kwargs?: {\n inputs?: Record<string, unknown>;\n }): Promise<any> | any;\n /**\n * Called at the start of a Tool run, with the tool name and input\n * and the run ID.\n */\n handleToolStart?(tool: Serialized, input: string, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>, runName?: string): Promise<any> | any;\n /**\n * Called if a Tool run encounters an error\n */\n handleToolError?(err: Error, runId: string, parentRunId?: string, tags?: string[]): Promise<any> | any;\n /**\n * Called at the end of a Tool run, with the tool output and the run ID.\n */\n handleToolEnd?(output: any, runId: string, parentRunId?: string, tags?: string[]): Promise<any> | any;\n handleText?(text: string, runId: string, parentRunId?: string, tags?: string[]): Promise<void> | void;\n /**\n * Called when an agent is about to execute an action,\n * with the action and the run ID.\n */\n handleAgentAction?(action: AgentAction, runId: string, parentRunId?: string, tags?: string[]): Promise<void> | void;\n /**\n * Called when an agent finishes execution, before it exits.\n * with the final output and the run ID.\n */\n handleAgentEnd?(action: AgentFinish, runId: string, parentRunId?: string, tags?: string[]): Promise<void> | void;\n handleRetrieverStart?(retriever: Serialized, query: string, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>, name?: string): Promise<any> | any;\n handleRetrieverEnd?(documents: DocumentInterface[], runId: string, parentRunId?: string, tags?: string[]): Promise<any> | any;\n handleRetrieverError?(err: Error, runId: string, parentRunId?: string, tags?: string[]): Promise<any> | any;\n handleCustomEvent?(eventName: string, data: any, runId: string, tags?: string[], metadata?: Record<string, any>): Promise<any> | any;\n}\n/**\n * Base interface for callbacks. All methods are optional. If a method is not\n * implemented, it will be ignored. If a method is implemented, it will be\n * called at the appropriate time. All methods are called with the run ID of\n * the LLM/ChatModel/Chain that is running, which is generated by the\n * CallbackManager.\n *\n * @interface\n */\nexport type CallbackHandlerMethods = BaseCallbackHandlerMethodsClass;\n/**\n * Interface for handlers that can indicate a preference for streaming responses.\n * When implemented, this allows the handler to signal whether it prefers to receive\n * streaming responses from language models rather than complete responses.\n */\nexport interface CallbackHandlerPrefersStreaming {\n readonly lc_prefer_streaming: boolean;\n}\nexport declare function callbackHandlerPrefersStreaming(x: BaseCallbackHandler): unknown;\n/**\n * Abstract base class for creating callback handlers in the LangChain\n * framework. It provides a set of optional methods that can be overridden\n * in derived classes to handle various events during the execution of a\n * LangChain application.\n */\nexport declare abstract class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass implements BaseCallbackHandlerInput, Serializable {\n lc_serializable: boolean;\n get lc_namespace(): [\"langchain_core\", \"callbacks\", string];\n get lc_secrets(): {\n [key: string]: string;\n } | undefined;\n get lc_attributes(): {\n [key: string]: string;\n } | undefined;\n get lc_aliases(): {\n [key: string]: string;\n } | undefined;\n get lc_serializable_keys(): string[] | undefined;\n /**\n * The name of the serializable. Override to provide an alias or\n * to preserve the serialized module name in minified environments.\n *\n * Implemented as a static method to support loading logic.\n */\n static lc_name(): string;\n /**\n * The final serialized identifier for the module.\n */\n get lc_id(): string[];\n lc_kwargs: SerializedFields;\n abstract name: string;\n ignoreLLM: boolean;\n ignoreChain: boolean;\n ignoreAgent: boolean;\n ignoreRetriever: boolean;\n ignoreCustomEvent: boolean;\n raiseError: boolean;\n awaitHandlers: boolean;\n constructor(input?: BaseCallbackHandlerInput);\n copy(): BaseCallbackHandler;\n toJSON(): Serialized;\n toJSONNotImplemented(): SerializedNotImplemented;\n static fromMethods(methods: CallbackHandlerMethods): {\n name: string;\n /**\n * Called at the start of an LLM or Chat Model run, with the prompt(s)\n * and the run ID.\n */\n handleLLMStart?(llm: Serialized, prompts: string[], runId: string, parentRunId?: string | undefined, extraParams?: Record<string, unknown> | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runName?: string | undefined): any;\n /**\n * Called when an LLM/ChatModel in `streaming` mode produces a new token\n */\n handleLLMNewToken?(token: string, idx: NewTokenIndices, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, fields?: HandleLLMNewTokenCallbackFields | undefined): any;\n /**\n * Called if an LLM/ChatModel run encounters an error\n */\n handleLLMError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, extraParams?: Record<string, unknown> | undefined): any;\n /**\n * Called at the end of an LLM/ChatModel run, with the output and the run ID.\n */\n handleLLMEnd?(output: LLMResult, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, extraParams?: Record<string, unknown> | undefined): any;\n /**\n * Called at the start of a Chat Model run, with the prompt(s)\n * and the run ID.\n */\n handleChatModelStart?(llm: Serialized, messages: BaseMessage<import(\"../messages/message.js\").MessageStructure, import(\"../messages/message.js\").MessageType>[][], runId: string, parentRunId?: string | undefined, extraParams?: Record<string, unknown> | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runName?: string | undefined): any;\n /**\n * Called at the start of a Chain run, with the chain name and inputs\n * and the run ID.\n */\n handleChainStart?(chain: Serialized, inputs: ChainValues, runId: string, runType?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runName?: string | undefined, parentRunId?: string | undefined, extra?: Record<string, unknown> | undefined): any;\n /**\n * Called if a Chain run encounters an error\n */\n handleChainError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, kwargs?: {\n inputs?: Record<string, unknown> | undefined;\n } | undefined): any;\n /**\n * Called at the end of a Chain run, with the outputs and the run ID.\n */\n handleChainEnd?(outputs: ChainValues, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, kwargs?: {\n inputs?: Record<string, unknown> | undefined;\n } | undefined): any;\n /**\n * Called at the start of a Tool run, with the tool name and input\n * and the run ID.\n */\n handleToolStart?(tool: Serialized, input: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runName?: string | undefined): any;\n /**\n * Called if a Tool run encounters an error\n */\n handleToolError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;\n /**\n * Called at the end of a Tool run, with the tool output and the run ID.\n */\n handleToolEnd?(output: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;\n handleText?(text: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): void | Promise<void>;\n /**\n * Called when an agent is about to execute an action,\n * with the action and the run ID.\n */\n handleAgentAction?(action: AgentAction, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): void | Promise<void>;\n /**\n * Called when an agent finishes execution, before it exits.\n * with the final output and the run ID.\n */\n handleAgentEnd?(action: AgentFinish, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): void | Promise<void>;\n handleRetrieverStart?(retriever: Serialized, query: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, name?: string | undefined): any;\n handleRetrieverEnd?(documents: DocumentInterface<Record<string, any>>[], runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;\n handleRetrieverError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;\n handleCustomEvent?(eventName: string, data: any, runId: string, tags?: string[] | undefined, metadata?: Record<string, any> | undefined): any;\n lc_serializable: boolean;\n get lc_namespace(): [\"langchain_core\", \"callbacks\", string];\n get lc_secrets(): {\n [key: string]: string;\n } | undefined;\n get lc_attributes(): {\n [key: string]: string;\n } | undefined;\n get lc_aliases(): {\n [key: string]: string;\n } | undefined;\n get lc_serializable_keys(): string[] | undefined;\n /**\n * The final serialized identifier for the module.\n */\n get lc_id(): string[];\n lc_kwargs: SerializedFields;\n ignoreLLM: boolean;\n ignoreChain: boolean;\n ignoreAgent: boolean;\n ignoreRetriever: boolean;\n ignoreCustomEvent: boolean;\n raiseError: boolean;\n awaitHandlers: boolean;\n copy(): BaseCallbackHandler;\n toJSON(): Serialized;\n toJSONNotImplemented(): SerializedNotImplemented;\n };\n}\nexport declare const isBaseCallbackHandler: (x: unknown) => boolean;\nexport {};\n//# sourceMappingURL=base.d.ts.map"],"mappings":";;;;;;;;;;KAOKY,KAAAA;;;AAD6D;AAOlE;AAaA;AAIYG,UAjBKF,wBAAAA,CAiB0B;EAQpBG,SAAAA,CAAAA,EAAAA,OAAAA;EAKER,WAAAA,CAAAA,EAAAA,OAAAA;EAAkFS,WAAAA,CAAAA,EAAAA,OAAAA;EAAqDA,eAAAA,CAAAA,EAAAA,OAAAA;EAA4CC,iBAAAA,CAAAA,EAAAA,OAAAA;EAWnMJ,aAAAA,CAAAA,EAAAA,OAAAA;EAAgFC,UAAAA,CAAAA,EAAAA,OAAAA;;;;;;AAQgBE,UApCxFH,eAAAA,CAoCwFG;EAA0BC,MAAAA,EAAAA,MAAAA;EAKpGV,UAAAA,EAAAA,MAAAA;;AAA0FS,KArC7GF,+BAAAA,GAqC6GE;EAAqDA,KAAAA,CAAAA,EApClKZ,eAoCkKY,GApChJb,mBAoCgJa;CA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BAMUT,oHAAoHS;;;;;;;;;oHAS3BC;;;;;+BAKrFhB,mGAAmGgB;;;;;4BAKtGf,mGAAmGe;qCAC1FV,oHAAoHS;mCACtHN,kBAAkBM;;4GAEuDA;;;;;;;;;;;;;;;;;eAiB7FP;;;;;;;;YAQHY;cACEd;4BACcC;;;cAGXiB"}
@@ -1 +1 @@
1
- {"version":3,"file":"chat_models.d.ts","names":["ZodType","ZodTypeV3","$ZodType","ZodTypeV4","BaseMessage","BaseMessageChunk","BaseMessageLike","AIMessageChunk","MessageOutputVersion","BasePromptValueInterface","LLMResult","ChatGenerationChunk","ChatResult","Generation","BaseLanguageModel","StructuredOutputMethodOptions","ToolDefinition","BaseLanguageModelCallOptions","BaseLanguageModelInput","BaseLanguageModelParams","CallbackManagerForLLMRun","Callbacks","RunnableConfig","BaseCache","StructuredToolInterface","StructuredToolParams","Runnable","RunnableToolLike","ToolChoice","Record","SerializedChatModel","SerializedLLM","BaseChatModelParams","BaseChatModelCallOptions","LangSmithParams","Array","BindToolsInput","BaseChatModel","RunOutput","CallOptions","OutputMessageType","Exclude","Omit","Partial","Promise","AsyncGenerator","messages","cache","llmStringKey","parsedOptions","handledOptions","SimpleChatModel"],"sources":["../../src/language_models/chat_models.d.ts"],"sourcesContent":["import type { ZodType as ZodTypeV3 } from \"zod/v3\";\nimport type { $ZodType as ZodTypeV4 } from \"zod/v4/core\";\nimport { type BaseMessage, BaseMessageChunk, type BaseMessageLike, AIMessageChunk, MessageOutputVersion } from \"../messages/index.js\";\nimport type { BasePromptValueInterface } from \"../prompt_values.js\";\nimport { LLMResult, ChatGenerationChunk, type ChatResult, type Generation } from \"../outputs.js\";\nimport { BaseLanguageModel, type StructuredOutputMethodOptions, type ToolDefinition, type BaseLanguageModelCallOptions, type BaseLanguageModelInput, type BaseLanguageModelParams } from \"./base.js\";\nimport { type CallbackManagerForLLMRun, type Callbacks } from \"../callbacks/manager.js\";\nimport type { RunnableConfig } from \"../runnables/config.js\";\nimport type { BaseCache } from \"../caches/index.js\";\nimport { StructuredToolInterface, StructuredToolParams } from \"../tools/index.js\";\nimport { Runnable, RunnableToolLike } from \"../runnables/base.js\";\nexport type ToolChoice = string | Record<string, any> | \"auto\" | \"any\";\n/**\n * Represents a serialized chat model.\n */\nexport type SerializedChatModel = {\n _model: string;\n _type: string;\n} & Record<string, any>;\n/**\n * Represents a serialized large language model.\n */\nexport type SerializedLLM = {\n _model: string;\n _type: string;\n} & Record<string, any>;\n/**\n * Represents the parameters for a base chat model.\n */\nexport type BaseChatModelParams = BaseLanguageModelParams & {\n /**\n * Whether to disable streaming.\n *\n * If streaming is bypassed, then `stream()` will defer to\n * `invoke()`.\n *\n * - If true, will always bypass streaming case.\n * - If false (default), will always use streaming case if available.\n */\n disableStreaming?: boolean;\n /**\n * Version of `AIMessage` output format to store in message content.\n *\n * `AIMessage.contentBlocks` will lazily parse the contents of `content` into a\n * standard format. This flag can be used to additionally store the standard format\n * as the message content, e.g., for serialization purposes.\n *\n * - \"v0\": provider-specific format in content (can lazily parse with `.contentBlocks`)\n * - \"v1\": standardized format in content (consistent with `.contentBlocks`)\n *\n * You can also set `LC_OUTPUT_VERSION` as an environment variable to \"v1\" to\n * enable this by default.\n *\n * @default \"v0\"\n */\n outputVersion?: MessageOutputVersion;\n};\n/**\n * Represents the call options for a base chat model.\n */\nexport type BaseChatModelCallOptions = BaseLanguageModelCallOptions & {\n /**\n * Specifies how the chat model should use tools.\n * @default undefined\n *\n * Possible values:\n * - \"auto\": The model may choose to use any of the provided tools, or none.\n * - \"any\": The model must use one of the provided tools.\n * - \"none\": The model must not use any tools.\n * - A string (not \"auto\", \"any\", or \"none\"): The name of a specific tool the model must use.\n * - An object: A custom schema specifying tool choice parameters. Specific to the provider.\n *\n * Note: Not all providers support tool_choice. An error will be thrown\n * if used with an unsupported model.\n */\n tool_choice?: ToolChoice;\n /**\n * Version of `AIMessage` output format to store in message content.\n *\n * `AIMessage.contentBlocks` will lazily parse the contents of `content` into a\n * standard format. This flag can be used to additionally store the standard format\n * as the message content, e.g., for serialization purposes.\n *\n * - \"v0\": provider-specific format in content (can lazily parse with `.contentBlocks`)\n * - \"v1\": standardized format in content (consistent with `.contentBlocks`)\n *\n * You can also set `LC_OUTPUT_VERSION` as an environment variable to \"v1\" to\n * enable this by default.\n *\n * @default \"v0\"\n */\n outputVersion?: MessageOutputVersion;\n};\nexport type LangSmithParams = {\n ls_provider?: string;\n ls_model_name?: string;\n ls_model_type: \"chat\";\n ls_temperature?: number;\n ls_max_tokens?: number;\n ls_stop?: Array<string>;\n};\nexport type BindToolsInput = StructuredToolInterface | Record<string, any> | ToolDefinition | RunnableToolLike | StructuredToolParams;\n/**\n * Base class for chat models. It extends the BaseLanguageModel class and\n * provides methods for generating chat based on input messages.\n */\nexport declare abstract class BaseChatModel<CallOptions extends BaseChatModelCallOptions = BaseChatModelCallOptions, OutputMessageType extends BaseMessageChunk = AIMessageChunk> extends BaseLanguageModel<OutputMessageType, CallOptions> {\n ParsedCallOptions: Omit<CallOptions, Exclude<keyof RunnableConfig, \"signal\" | \"timeout\" | \"maxConcurrency\">>;\n lc_namespace: string[];\n disableStreaming: boolean;\n outputVersion?: MessageOutputVersion;\n get callKeys(): string[];\n constructor(fields: BaseChatModelParams);\n _combineLLMOutput?(...llmOutputs: LLMResult[\"llmOutput\"][]): LLMResult[\"llmOutput\"];\n protected _separateRunnableConfigFromCallOptionsCompat(options?: Partial<CallOptions>): [RunnableConfig, this[\"ParsedCallOptions\"]];\n /**\n * Bind tool-like objects to this chat model.\n *\n * @param tools A list of tool definitions to bind to this chat model.\n * Can be a structured tool, an OpenAI formatted tool, or an object\n * matching the provider's specific tool schema.\n * @param kwargs Any additional parameters to bind.\n */\n bindTools?(tools: BindToolsInput[], kwargs?: Partial<CallOptions>): Runnable<BaseLanguageModelInput, OutputMessageType, CallOptions>;\n /**\n * Invokes the chat model with a single input.\n * @param input The input for the language model.\n * @param options The call options.\n * @returns A Promise that resolves to a BaseMessageChunk.\n */\n invoke(input: BaseLanguageModelInput, options?: CallOptions): Promise<OutputMessageType>;\n _streamResponseChunks(_messages: BaseMessage[], _options: this[\"ParsedCallOptions\"], _runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;\n _streamIterator(input: BaseLanguageModelInput, options?: CallOptions): AsyncGenerator<OutputMessageType>;\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams;\n /** @ignore */\n _generateUncached(messages: BaseMessageLike[][], parsedOptions: this[\"ParsedCallOptions\"], handledOptions: RunnableConfig, startedRunManagers?: CallbackManagerForLLMRun[]): Promise<LLMResult>;\n _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions }: {\n messages: BaseMessageLike[][];\n cache: BaseCache<Generation[]>;\n llmStringKey: string;\n parsedOptions: any;\n handledOptions: RunnableConfig;\n }): Promise<LLMResult & {\n missingPromptIndices: number[];\n startedRunManagers?: CallbackManagerForLLMRun[];\n }>;\n /**\n * Generates chat based on the input messages.\n * @param messages An array of arrays of BaseMessage instances.\n * @param options The call options or an array of stop sequences.\n * @param callbacks The callbacks for the language model.\n * @returns A Promise that resolves to an LLMResult.\n */\n generate(messages: BaseMessageLike[][], options?: string[] | CallOptions, callbacks?: Callbacks): Promise<LLMResult>;\n /**\n * Get the parameters used to invoke the model\n */\n invocationParams(_options?: this[\"ParsedCallOptions\"]): any;\n _modelType(): string;\n abstract _llmType(): string;\n /**\n * Generates a prompt based on the input prompt values.\n * @param promptValues An array of BasePromptValue instances.\n * @param options The call options or an array of stop sequences.\n * @param callbacks The callbacks for the language model.\n * @returns A Promise that resolves to an LLMResult.\n */\n generatePrompt(promptValues: BasePromptValueInterface[], options?: string[] | CallOptions, callbacks?: Callbacks): Promise<LLMResult>;\n abstract _generate(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: ZodTypeV4<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: ZodTypeV4<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {\n raw: BaseMessage;\n parsed: RunOutput;\n }>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: ZodTypeV3<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: ZodTypeV3<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {\n raw: BaseMessage;\n parsed: RunOutput;\n }>;\n}\n/**\n * An abstract class that extends BaseChatModel and provides a simple\n * implementation of _generate.\n */\nexport declare abstract class SimpleChatModel<CallOptions extends BaseChatModelCallOptions = BaseChatModelCallOptions> extends BaseChatModel<CallOptions> {\n abstract _call(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<string>;\n _generate(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n}\n//# sourceMappingURL=chat_models.d.ts.map"],"mappings":";;;;;;;;;;;;;;;;;;KAWY4B,UAAAA,YAAsBC;;;;KAItBC,mBAAAA;;;AAJZ,CAAA,GAOID,MAPQD,CAAAA,MAAU,EAAA,GAAA,CAAA;AAItB;AAOA;AAOA;AA+BYK,KAtCAF,aAAAA,GAsCAE;EAA2BhB,MAAAA,EAAAA,MAAAA;EAerBW,KAAAA,EAAAA,MAAAA;CAgBEpB,GAlEhBqB,MAkEgBrB,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA;AAAoB;AAExC;AAQA;AAA6BgB,KAxEjBQ,mBAAAA,GAAsBb,uBAwELK,GAAAA;EAA0BK;;;;AAA8E;AAKrI;;;;EA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1B,SAAUmC,aAAaT,8BAA8Bd,uCAAuCW,SAASR,wBAAwBoB;yCACtLT,sBAAsBA,mCAAmC1B,SAAUmC,aAAaT,8BAA8Bd,sCAAsCW,SAASR;SAC3Ld;YACGkC;;yCAE2BT,sBAAsBA,mCAAmC5B,QAAUqC,aAAaT,8BAA8Bd,uCAAuCW,SAASR,wBAAwBoB;yCACtLT,sBAAsBA,mCAAmC5B,QAAUqC,aAAaT,8BAA8Bd,sCAAsCW,SAASR;SAC3Ld;YACGkC;;;;;;;uBAOca,oCAAoClB,2BAA2BA,kCAAkCI,cAAcE;2BAChHnC,gEAAgEgB,2BAA2BwB;sBAChGxC,gEAAgEgB,2BAA2BwB,QAAQhC"}
1
+ {"version":3,"file":"chat_models.d.ts","names":["ZodType","ZodTypeV3","$ZodType","ZodTypeV4","BaseMessage","BaseMessageChunk","BaseMessageLike","AIMessageChunk","MessageOutputVersion","BasePromptValueInterface","LLMResult","ChatGenerationChunk","ChatResult","Generation","BaseLanguageModel","StructuredOutputMethodOptions","ToolDefinition","BaseLanguageModelCallOptions","BaseLanguageModelInput","BaseLanguageModelParams","CallbackManagerForLLMRun","Callbacks","RunnableConfig","BaseCache","StructuredToolInterface","StructuredToolParams","Runnable","RunnableToolLike","ToolChoice","Record","SerializedChatModel","SerializedLLM","BaseChatModelParams","BaseChatModelCallOptions","LangSmithParams","Array","BindToolsInput","BaseChatModel","RunOutput","CallOptions","OutputMessageType","Exclude","Omit","Partial","Promise","AsyncGenerator","messages","cache","llmStringKey","parsedOptions","handledOptions","SimpleChatModel"],"sources":["../../src/language_models/chat_models.d.ts"],"sourcesContent":["import type { ZodType as ZodTypeV3 } from \"zod/v3\";\nimport type { $ZodType as ZodTypeV4 } from \"zod/v4/core\";\nimport { type BaseMessage, BaseMessageChunk, type BaseMessageLike, AIMessageChunk, MessageOutputVersion } from \"../messages/index.js\";\nimport type { BasePromptValueInterface } from \"../prompt_values.js\";\nimport { LLMResult, ChatGenerationChunk, type ChatResult, type Generation } from \"../outputs.js\";\nimport { BaseLanguageModel, type StructuredOutputMethodOptions, type ToolDefinition, type BaseLanguageModelCallOptions, type BaseLanguageModelInput, type BaseLanguageModelParams } from \"./base.js\";\nimport { type CallbackManagerForLLMRun, type Callbacks } from \"../callbacks/manager.js\";\nimport type { RunnableConfig } from \"../runnables/config.js\";\nimport type { BaseCache } from \"../caches/index.js\";\nimport { StructuredToolInterface, StructuredToolParams } from \"../tools/index.js\";\nimport { Runnable, RunnableToolLike } from \"../runnables/base.js\";\nexport type ToolChoice = string | Record<string, any> | \"auto\" | \"any\";\n/**\n * Represents a serialized chat model.\n */\nexport type SerializedChatModel = {\n _model: string;\n _type: string;\n} & Record<string, any>;\n/**\n * Represents a serialized large language model.\n */\nexport type SerializedLLM = {\n _model: string;\n _type: string;\n} & Record<string, any>;\n/**\n * Represents the parameters for a base chat model.\n */\nexport type BaseChatModelParams = BaseLanguageModelParams & {\n /**\n * Whether to disable streaming.\n *\n * If streaming is bypassed, then `stream()` will defer to\n * `invoke()`.\n *\n * - If true, will always bypass streaming case.\n * - If false (default), will always use streaming case if available.\n */\n disableStreaming?: boolean;\n /**\n * Version of `AIMessage` output format to store in message content.\n *\n * `AIMessage.contentBlocks` will lazily parse the contents of `content` into a\n * standard format. This flag can be used to additionally store the standard format\n * as the message content, e.g., for serialization purposes.\n *\n * - \"v0\": provider-specific format in content (can lazily parse with `.contentBlocks`)\n * - \"v1\": standardized format in content (consistent with `.contentBlocks`)\n *\n * You can also set `LC_OUTPUT_VERSION` as an environment variable to \"v1\" to\n * enable this by default.\n *\n * @default \"v0\"\n */\n outputVersion?: MessageOutputVersion;\n};\n/**\n * Represents the call options for a base chat model.\n */\nexport type BaseChatModelCallOptions = BaseLanguageModelCallOptions & {\n /**\n * Specifies how the chat model should use tools.\n * @default undefined\n *\n * Possible values:\n * - \"auto\": The model may choose to use any of the provided tools, or none.\n * - \"any\": The model must use one of the provided tools.\n * - \"none\": The model must not use any tools.\n * - A string (not \"auto\", \"any\", or \"none\"): The name of a specific tool the model must use.\n * - An object: A custom schema specifying tool choice parameters. Specific to the provider.\n *\n * Note: Not all providers support tool_choice. An error will be thrown\n * if used with an unsupported model.\n */\n tool_choice?: ToolChoice;\n /**\n * Version of `AIMessage` output format to store in message content.\n *\n * `AIMessage.contentBlocks` will lazily parse the contents of `content` into a\n * standard format. This flag can be used to additionally store the standard format\n * as the message content, e.g., for serialization purposes.\n *\n * - \"v0\": provider-specific format in content (can lazily parse with `.contentBlocks`)\n * - \"v1\": standardized format in content (consistent with `.contentBlocks`)\n *\n * You can also set `LC_OUTPUT_VERSION` as an environment variable to \"v1\" to\n * enable this by default.\n *\n * @default \"v0\"\n */\n outputVersion?: MessageOutputVersion;\n};\nexport type LangSmithParams = {\n ls_provider?: string;\n ls_model_name?: string;\n ls_model_type: \"chat\";\n ls_temperature?: number;\n ls_max_tokens?: number;\n ls_stop?: Array<string>;\n};\nexport type BindToolsInput = StructuredToolInterface | Record<string, any> | ToolDefinition | RunnableToolLike | StructuredToolParams;\n/**\n * Base class for chat models. It extends the BaseLanguageModel class and\n * provides methods for generating chat based on input messages.\n */\nexport declare abstract class BaseChatModel<CallOptions extends BaseChatModelCallOptions = BaseChatModelCallOptions, OutputMessageType extends BaseMessageChunk = AIMessageChunk> extends BaseLanguageModel<OutputMessageType, CallOptions> {\n ParsedCallOptions: Omit<CallOptions, Exclude<keyof RunnableConfig, \"signal\" | \"timeout\" | \"maxConcurrency\">>;\n lc_namespace: string[];\n disableStreaming: boolean;\n outputVersion?: MessageOutputVersion;\n get callKeys(): string[];\n constructor(fields: BaseChatModelParams);\n _combineLLMOutput?(...llmOutputs: LLMResult[\"llmOutput\"][]): LLMResult[\"llmOutput\"];\n protected _separateRunnableConfigFromCallOptionsCompat(options?: Partial<CallOptions>): [RunnableConfig, this[\"ParsedCallOptions\"]];\n /**\n * Bind tool-like objects to this chat model.\n *\n * @param tools A list of tool definitions to bind to this chat model.\n * Can be a structured tool, an OpenAI formatted tool, or an object\n * matching the provider's specific tool schema.\n * @param kwargs Any additional parameters to bind.\n */\n bindTools?(tools: BindToolsInput[], kwargs?: Partial<CallOptions>): Runnable<BaseLanguageModelInput, OutputMessageType, CallOptions>;\n /**\n * Invokes the chat model with a single input.\n * @param input The input for the language model.\n * @param options The call options.\n * @returns A Promise that resolves to a BaseMessageChunk.\n */\n invoke(input: BaseLanguageModelInput, options?: CallOptions): Promise<OutputMessageType>;\n _streamResponseChunks(_messages: BaseMessage[], _options: this[\"ParsedCallOptions\"], _runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;\n _streamIterator(input: BaseLanguageModelInput, options?: CallOptions): AsyncGenerator<OutputMessageType>;\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams;\n /** @ignore */\n _generateUncached(messages: BaseMessageLike[][], parsedOptions: this[\"ParsedCallOptions\"], handledOptions: RunnableConfig, startedRunManagers?: CallbackManagerForLLMRun[]): Promise<LLMResult>;\n _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions }: {\n messages: BaseMessageLike[][];\n cache: BaseCache<Generation[]>;\n llmStringKey: string;\n parsedOptions: any;\n handledOptions: RunnableConfig;\n }): Promise<LLMResult & {\n missingPromptIndices: number[];\n startedRunManagers?: CallbackManagerForLLMRun[];\n }>;\n /**\n * Generates chat based on the input messages.\n * @param messages An array of arrays of BaseMessage instances.\n * @param options The call options or an array of stop sequences.\n * @param callbacks The callbacks for the language model.\n * @returns A Promise that resolves to an LLMResult.\n */\n generate(messages: BaseMessageLike[][], options?: string[] | CallOptions, callbacks?: Callbacks): Promise<LLMResult>;\n /**\n * Get the parameters used to invoke the model\n */\n invocationParams(_options?: this[\"ParsedCallOptions\"]): any;\n _modelType(): string;\n abstract _llmType(): string;\n /**\n * Generates a prompt based on the input prompt values.\n * @param promptValues An array of BasePromptValue instances.\n * @param options The call options or an array of stop sequences.\n * @param callbacks The callbacks for the language model.\n * @returns A Promise that resolves to an LLMResult.\n */\n generatePrompt(promptValues: BasePromptValueInterface[], options?: string[] | CallOptions, callbacks?: Callbacks): Promise<LLMResult>;\n abstract _generate(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: ZodTypeV4<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: ZodTypeV4<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {\n raw: BaseMessage;\n parsed: RunOutput;\n }>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: ZodTypeV3<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: ZodTypeV3<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {\n raw: BaseMessage;\n parsed: RunOutput;\n }>;\n}\n/**\n * An abstract class that extends BaseChatModel and provides a simple\n * implementation of _generate.\n */\nexport declare abstract class SimpleChatModel<CallOptions extends BaseChatModelCallOptions = BaseChatModelCallOptions> extends BaseChatModel<CallOptions> {\n abstract _call(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<string>;\n _generate(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n}\n//# sourceMappingURL=chat_models.d.ts.map"],"mappings":";;;;;;;;;;;;;;;;;;KAWY4B,UAAAA,YAAsBC;;;;KAItBC,mBAAAA;;;AAJZ,CAAA,GAOID,MAPQD,CAAAA,MAAU,EAAA,GAAA,CAAA;AAItB;AAOA;AAOA;AA+BYK,KAtCAF,aAAAA,GAsCAE;EAA2BhB,M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CAAAA,EAjCjCS,SAiCiCT,CAAAA,EAjCrBgC,OAiCqBhC,CAjCbF,SAiCaE,CAAAA;EAARgC;;AAFyB;;;;;;;;;;;+BAjB3GnC,iDAAiD8B,yBAAyBlB,YAAYuB,QAAQlC;+BAC9FN,gEAAgEgB,2BAA2BwB,QAAQhC;yCACzFiB,sBAAsBA,mCAAmC1B,SAAUmC,aAAaT,8BAA8Bd,uCAAuCW,SAASR,wBAAwBoB;yCACtLT,sBAAsBA,mCAAmC1B,SAAUmC,aAAaT,8BAA8Bd,sCAAsCW,SAASR;SAC3Ld;YACGkC;;yCAE2BT,sBAAsBA,mCAAmC5B,QAAUqC,aAAaT,8BAA8Bd,uCAAuCW,SAASR,wBAAwBoB;yCACtLT,sBAAsBA,mCAAmC5B,QAAUqC,aAAaT,8BAA8Bd,sCAAsCW,SAASR;SAC3Ld;YACGkC;;;;;;;uBAOca,oCAAoClB,2BAA2BA,kCAAkCI,cAAcE;2BAChHnC,gEAAgEgB,2BAA2BwB;sBAChGxC,gEAAgEgB,2BAA2BwB,QAAQhC"}
@@ -1,10 +1,16 @@
1
1
  const require_map_keys = require('./map_keys.cjs');
2
+ const require_validation = require('./validation.cjs');
2
3
  const require_load_serializable = require('./serializable.cjs');
3
4
  const require_utils_env = require('../utils/env.cjs');
4
5
  const require_import_constants = require('./import_constants.cjs');
5
6
  const require_import_map = require('./import_map.cjs');
6
7
 
7
8
  //#region src/load/index.ts
9
+ /**
10
+ * Default maximum recursion depth for deserialization.
11
+ * This provides protection against DoS attacks via deeply nested structures.
12
+ */
13
+ const DEFAULT_MAX_DEPTH = 50;
8
14
  function combineAliasesAndInvert(constructor) {
9
15
  const aliases = {};
10
16
  for (let current = constructor; current && current.prototype; current = Object.getPrototypeOf(current)) Object.assign(aliases, Reflect.get(current.prototype, "lc_aliases"));
@@ -13,24 +19,44 @@ function combineAliasesAndInvert(constructor) {
13
19
  return acc;
14
20
  }, {});
15
21
  }
22
+ /**
23
+ * Recursively revive a value, handling escape markers and LC objects.
24
+ *
25
+ * This function handles:
26
+ * 1. Escaped dicts - unwrapped and returned as plain objects
27
+ * 2. LC secret objects - resolved from secretsMap or env
28
+ * 3. LC constructor objects - instantiated
29
+ * 4. Regular objects/arrays - recursed into
30
+ */
16
31
  async function reviver(value) {
17
- const { optionalImportsMap = {}, optionalImportEntrypoints: optionalImportEntrypoints$1 = [], importMap = {}, secretsMap = {}, path = ["$"] } = this;
32
+ const { optionalImportsMap, optionalImportEntrypoints: optionalImportEntrypoints$1, importMap, secretsMap, secretsFromEnv, path, depth, maxDepth } = this;
18
33
  const pathStr = path.join(".");
19
- if (typeof value === "object" && value !== null && !Array.isArray(value) && "lc" in value && "type" in value && "id" in value && value.lc === 1 && value.type === "secret") {
20
- const serialized = value;
34
+ if (depth > maxDepth) throw new Error(`Maximum recursion depth (${maxDepth}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);
35
+ if (typeof value !== "object" || value == null) return value;
36
+ if (Array.isArray(value)) return Promise.all(value.map((v, i) => reviver.call({
37
+ ...this,
38
+ path: [...path, `${i}`],
39
+ depth: depth + 1
40
+ }, v)));
41
+ const record = value;
42
+ if (require_validation.isEscapedObject(record)) return require_validation.unescapeValue(record);
43
+ if ("lc" in record && "type" in record && "id" in record && record.lc === 1 && record.type === "secret") {
44
+ const serialized = record;
21
45
  const [key] = serialized.id;
22
46
  if (key in secretsMap) return secretsMap[key];
23
- else {
47
+ else if (secretsFromEnv) {
24
48
  const secretValueInEnv = require_utils_env.getEnvironmentVariable(key);
25
49
  if (secretValueInEnv) return secretValueInEnv;
26
- else throw new Error(`Missing key "${key}" for ${pathStr} in load(secretsMap={})`);
27
50
  }
28
- } else if (typeof value === "object" && value !== null && !Array.isArray(value) && "lc" in value && "type" in value && "id" in value && value.lc === 1 && value.type === "not_implemented") {
29
- const serialized = value;
51
+ throw new Error(`Missing secret "${key}" at ${pathStr}`);
52
+ }
53
+ if ("lc" in record && "type" in record && "id" in record && record.lc === 1 && record.type === "not_implemented") {
54
+ const serialized = record;
30
55
  const str = JSON.stringify(serialized);
31
56
  throw new Error(`Trying to load an object that doesn't implement serialization: ${pathStr} -> ${str}`);
32
- } else if (typeof value === "object" && value !== null && !Array.isArray(value) && "lc" in value && "type" in value && "id" in value && "kwargs" in value && value.lc === 1) {
33
- const serialized = value;
57
+ }
58
+ if ("lc" in record && "type" in record && "id" in record && "kwargs" in record && record.lc === 1 && record.type === "constructor") {
59
+ const serialized = record;
34
60
  const str = JSON.stringify(serialized);
35
61
  const [name, ...namespaceReverse] = serialized.id.slice().reverse();
36
62
  const namespace = namespaceReverse.reverse();
@@ -64,26 +90,60 @@ async function reviver(value) {
64
90
  if (typeof builder !== "function") throw new Error(`Invalid identifer: ${pathStr} -> ${str}`);
65
91
  const kwargs = await reviver.call({
66
92
  ...this,
67
- path: [...path, "kwargs"]
93
+ path: [...path, "kwargs"],
94
+ depth: depth + 1
68
95
  }, serialized.kwargs);
69
- if (serialized.type === "constructor") {
70
- const instance = new builder(require_map_keys.mapKeys(kwargs, require_map_keys.keyFromJson, combineAliasesAndInvert(builder)));
71
- Object.defineProperty(instance.constructor, "name", { value: name });
72
- return instance;
73
- } else throw new Error(`Invalid type: ${pathStr} -> ${str}`);
74
- } else if (typeof value === "object" && value !== null) if (Array.isArray(value)) return Promise.all(value.map((v, i) => reviver.call({
75
- ...this,
76
- path: [...path, `${i}`]
77
- }, v)));
78
- else return Object.fromEntries(await Promise.all(Object.entries(value).map(async ([key, value$1]) => [key, await reviver.call({
96
+ const instance = new builder(require_map_keys.mapKeys(kwargs, require_map_keys.keyFromJson, combineAliasesAndInvert(builder)));
97
+ Object.defineProperty(instance.constructor, "name", { value: name });
98
+ return instance;
99
+ }
100
+ const result = {};
101
+ for (const [key, val] of Object.entries(record)) result[key] = await reviver.call({
79
102
  ...this,
80
- path: [...path, key]
81
- }, value$1)])));
82
- return value;
103
+ path: [...path, key],
104
+ depth: depth + 1
105
+ }, val);
106
+ return result;
83
107
  }
84
- async function load(text, mappings) {
108
+ /**
109
+ * Load a LangChain object from a JSON string.
110
+ *
111
+ * @param text - The JSON string to parse and load.
112
+ * @param options - Options for loading.
113
+ * @returns The loaded LangChain object.
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * import { load } from "@langchain/core/load";
118
+ * import { AIMessage } from "@langchain/core/messages";
119
+ *
120
+ * // Basic usage - secrets must be provided explicitly
121
+ * const msg = await load<AIMessage>(jsonString);
122
+ *
123
+ * // With secrets from a map
124
+ * const msg = await load<AIMessage>(jsonString, {
125
+ * secretsMap: { OPENAI_API_KEY: "sk-..." }
126
+ * });
127
+ *
128
+ * // Allow loading secrets from environment (use with caution)
129
+ * const msg = await load<AIMessage>(jsonString, {
130
+ * secretsFromEnv: true
131
+ * });
132
+ * ```
133
+ */
134
+ async function load(text, options) {
85
135
  const json = JSON.parse(text);
86
- return reviver.call({ ...mappings }, json);
136
+ const context = {
137
+ optionalImportsMap: options?.optionalImportsMap ?? {},
138
+ optionalImportEntrypoints: options?.optionalImportEntrypoints ?? [],
139
+ secretsMap: options?.secretsMap ?? {},
140
+ secretsFromEnv: options?.secretsFromEnv ?? false,
141
+ importMap: options?.importMap ?? {},
142
+ path: ["$"],
143
+ depth: 0,
144
+ maxDepth: options?.maxDepth ?? DEFAULT_MAX_DEPTH
145
+ };
146
+ return reviver.call(context, json);
87
147
  }
88
148
 
89
149
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["constructor: typeof Serializable","aliases: { [key: string]: string }","value: unknown","getEnvironmentVariable","coreImportMap","module:\n | (typeof importMaps)[\"langchain_core\"][keyof (typeof importMaps)[\"langchain_core\"]]\n | (typeof importMaps)[\"langchain\"][keyof (typeof importMaps)[\"langchain\"]]\n | OptionalImportMap[keyof OptionalImportMap]\n | null","defaultOptionalImportEntrypoints","optionalImportEntrypoints","module","finalImportMap:\n | (typeof importMaps)[\"langchain\"]\n | (typeof importMaps)[\"langchain_core\"]","importMapKey: string","get_lc_unique_name","mapKeys","keyFromJson","value","text: string","mappings?: {\n secretsMap?: SecretMap;\n optionalImportsMap?: OptionalImportMap;\n optionalImportEntrypoints?: string[];\n importMap?: Record<string, unknown>;\n }"],"sources":["../../src/load/index.ts"],"sourcesContent":["import {\n Serializable,\n SerializedConstructor,\n SerializedNotImplemented,\n SerializedSecret,\n get_lc_unique_name,\n} from \"./serializable.js\";\nimport { optionalImportEntrypoints as defaultOptionalImportEntrypoints } from \"./import_constants.js\";\nimport * as coreImportMap from \"./import_map.js\";\nimport type { OptionalImportMap, SecretMap } from \"./import_type.js\";\nimport { type SerializedFields, keyFromJson, mapKeys } from \"./map_keys.js\";\nimport { getEnvironmentVariable } from \"../utils/env.js\";\n\nfunction combineAliasesAndInvert(constructor: typeof Serializable) {\n const aliases: { [key: string]: string } = {};\n for (\n let current = constructor;\n current && current.prototype;\n current = Object.getPrototypeOf(current)\n ) {\n Object.assign(aliases, Reflect.get(current.prototype, \"lc_aliases\"));\n }\n return Object.entries(aliases).reduce((acc, [key, value]) => {\n acc[value] = key;\n return acc;\n }, {} as Record<string, string>);\n}\n\nasync function reviver(\n this: {\n optionalImportsMap?: OptionalImportMap;\n optionalImportEntrypoints?: string[];\n secretsMap?: SecretMap;\n importMap?: Record<string, unknown>;\n path?: string[];\n },\n value: unknown\n): Promise<unknown> {\n const {\n optionalImportsMap = {},\n optionalImportEntrypoints = [],\n importMap = {},\n secretsMap = {},\n path = [\"$\"],\n } = this;\n const pathStr = path.join(\".\");\n if (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n \"lc\" in value &&\n \"type\" in value &&\n \"id\" in value &&\n value.lc === 1 &&\n value.type === \"secret\"\n ) {\n const serialized = value as SerializedSecret;\n const [key] = serialized.id;\n if (key in secretsMap) {\n return secretsMap[key as keyof SecretMap];\n } else {\n const secretValueInEnv = getEnvironmentVariable(key);\n if (secretValueInEnv) {\n return secretValueInEnv;\n } else {\n throw new Error(\n `Missing key \"${key}\" for ${pathStr} in load(secretsMap={})`\n );\n }\n }\n } else if (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n \"lc\" in value &&\n \"type\" in value &&\n \"id\" in value &&\n value.lc === 1 &&\n value.type === \"not_implemented\"\n ) {\n const serialized = value as SerializedNotImplemented;\n const str = JSON.stringify(serialized);\n throw new Error(\n `Trying to load an object that doesn't implement serialization: ${pathStr} -> ${str}`\n );\n } else if (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n \"lc\" in value &&\n \"type\" in value &&\n \"id\" in value &&\n \"kwargs\" in value &&\n value.lc === 1\n ) {\n const serialized = value as SerializedConstructor;\n const str = JSON.stringify(serialized);\n const [name, ...namespaceReverse] = serialized.id.slice().reverse();\n const namespace = namespaceReverse.reverse();\n const importMaps = { langchain_core: coreImportMap, langchain: importMap };\n\n let module:\n | (typeof importMaps)[\"langchain_core\"][keyof (typeof importMaps)[\"langchain_core\"]]\n | (typeof importMaps)[\"langchain\"][keyof (typeof importMaps)[\"langchain\"]]\n | OptionalImportMap[keyof OptionalImportMap]\n | null = null;\n\n const optionalImportNamespaceAliases = [namespace.join(\"/\")];\n if (namespace[0] === \"langchain_community\") {\n optionalImportNamespaceAliases.push(\n [\"langchain\", ...namespace.slice(1)].join(\"/\")\n );\n }\n const matchingNamespaceAlias = optionalImportNamespaceAliases.find(\n (alias) => alias in optionalImportsMap\n );\n if (\n defaultOptionalImportEntrypoints\n .concat(optionalImportEntrypoints)\n .includes(namespace.join(\"/\")) ||\n matchingNamespaceAlias\n ) {\n if (matchingNamespaceAlias !== undefined) {\n module = await optionalImportsMap[\n matchingNamespaceAlias as keyof typeof optionalImportsMap\n ];\n } else {\n throw new Error(\n `Missing key \"${namespace.join(\n \"/\"\n )}\" for ${pathStr} in load(optionalImportsMap={})`\n );\n }\n } else {\n let finalImportMap:\n | (typeof importMaps)[\"langchain\"]\n | (typeof importMaps)[\"langchain_core\"];\n // Currently, we only support langchain and langchain_core imports.\n if (namespace[0] === \"langchain\" || namespace[0] === \"langchain_core\") {\n finalImportMap = importMaps[namespace[0]];\n namespace.shift();\n } else {\n throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);\n }\n\n // The root namespace \"langchain\" is not a valid import.\n if (namespace.length === 0) {\n throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);\n }\n\n // Find the longest matching namespace.\n let importMapKey: string;\n do {\n importMapKey = namespace.join(\"__\");\n if (importMapKey in finalImportMap) {\n break;\n } else {\n namespace.pop();\n }\n } while (namespace.length > 0);\n\n // If no matching namespace is found, throw an error.\n if (importMapKey in finalImportMap) {\n module = finalImportMap[importMapKey as keyof typeof finalImportMap];\n }\n }\n\n if (typeof module !== \"object\" || module === null) {\n throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);\n }\n\n // Extract the builder from the import map.\n const builder =\n // look for a named export with the same name as the class\n module[name as keyof typeof module] ??\n // look for an export with a lc_name property matching the class name\n // this is necessary for classes that are minified\n Object.values(module).find(\n (v) =>\n typeof v === \"function\" &&\n get_lc_unique_name(v as typeof Serializable) === name\n );\n if (typeof builder !== \"function\") {\n throw new Error(`Invalid identifer: ${pathStr} -> ${str}`);\n }\n\n // Recurse on the arguments, which may be serialized objects themselves\n const kwargs = await reviver.call(\n { ...this, path: [...path, \"kwargs\"] },\n serialized.kwargs\n );\n\n // Construct the object\n if (serialized.type === \"constructor\") {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const instance = new (builder as any)(\n mapKeys(\n kwargs as SerializedFields,\n keyFromJson,\n combineAliasesAndInvert(builder)\n )\n );\n\n // Minification in severless/edge runtimes will mange the\n // name of classes presented in traces. As the names in import map\n // are present as-is even with minification, use these names instead\n Object.defineProperty(instance.constructor, \"name\", { value: name });\n\n return instance;\n } else {\n throw new Error(`Invalid type: ${pathStr} -> ${str}`);\n }\n } else if (typeof value === \"object\" && value !== null) {\n if (Array.isArray(value)) {\n return Promise.all(\n value.map((v, i) =>\n reviver.call({ ...this, path: [...path, `${i}`] }, v)\n )\n );\n } else {\n return Object.fromEntries(\n await Promise.all(\n Object.entries(value).map(async ([key, value]) => [\n key,\n await reviver.call({ ...this, path: [...path, key] }, value),\n ])\n )\n );\n }\n }\n return value;\n}\n\nexport async function load<T>(\n text: string,\n mappings?: {\n secretsMap?: SecretMap;\n optionalImportsMap?: OptionalImportMap;\n optionalImportEntrypoints?: string[];\n importMap?: Record<string, unknown>;\n }\n): Promise<T> {\n const json = JSON.parse(text);\n return reviver.call({ ...mappings }, json) as Promise<T>;\n}\n"],"mappings":";;;;;;;AAaA,SAAS,wBAAwBA,aAAkC;CACjE,MAAMC,UAAqC,CAAE;AAC7C,MACE,IAAI,UAAU,aACd,WAAW,QAAQ,WACnB,UAAU,OAAO,eAAe,QAAQ,EAExC,OAAO,OAAO,SAAS,QAAQ,IAAI,QAAQ,WAAW,aAAa,CAAC;AAEtE,QAAO,OAAO,QAAQ,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,MAAM,KAAK;EAC3D,IAAI,SAAS;AACb,SAAO;CACR,GAAE,CAAE,EAA2B;AACjC;AAED,eAAe,QAQbC,OACkB;CAClB,MAAM,EACJ,qBAAqB,CAAE,GACvB,yDAA4B,CAAE,GAC9B,YAAY,CAAE,GACd,aAAa,CAAE,GACf,OAAO,CAAC,GAAI,GACb,GAAG;CACJ,MAAM,UAAU,KAAK,KAAK,IAAI;AAC9B,KACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,QAAQ,SACR,UAAU,SACV,QAAQ,SACR,MAAM,OAAO,KACb,MAAM,SAAS,UACf;EACA,MAAM,aAAa;EACnB,MAAM,CAAC,IAAI,GAAG,WAAW;AACzB,MAAI,OAAO,WACT,QAAO,WAAW;OACb;GACL,MAAM,mBAAmBC,yCAAuB,IAAI;AACpD,OAAI,iBACF,QAAO;OAEP,OAAM,IAAI,MACR,CAAC,aAAa,EAAE,IAAI,MAAM,EAAE,QAAQ,uBAAuB,CAAC;EAGjE;CACF,WACC,OAAO,U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,OAAO,QAAQ,MAAM,CAAC,IAAI,OAAO,CAAC,KAAKC,QAAM,KAAK,CAChD,KACA,MAAM,QAAQ,KAAK;EAAE,GAAG;EAAM,MAAM,CAAC,GAAG,MAAM,GAAI;CAAE,GAAEA,QAAM,AAC7D,EAAC,CACH,CACF;AAGL,QAAO;AACR;AAED,eAAsB,KACpBC,MACAC,UAMY;CACZ,MAAM,OAAO,KAAK,MAAM,KAAK;AAC7B,QAAO,QAAQ,KAAK,EAAE,GAAG,SAAU,GAAE,KAAK;AAC3C"}
1
+ {"version":3,"file":"index.cjs","names":["constructor: typeof Serializable","aliases: { [key: string]: string }","value: unknown","isEscapedObject","unescapeValue","getEnvironmentVariable","coreImportMap","module:\n | (typeof importMaps)[\"langchain_core\"][keyof (typeof importMaps)[\"langchain_core\"]]\n | (typeof importMaps)[\"langchain\"][keyof (typeof importMaps)[\"langchain\"]]\n | OptionalImportMap[keyof OptionalImportMap]\n | null","defaultOptionalImportEntrypoints","optionalImportEntrypoints","module","finalImportMap:\n | (typeof importMaps)[\"langchain\"]\n | (typeof importMaps)[\"langchain_core\"]","importMapKey: string","get_lc_unique_name","mapKeys","keyFromJson","result: Record<string, unknown>","text: string","options?: LoadOptions","context: ReviverContext"],"sources":["../../src/load/index.ts"],"sourcesContent":["/**\n * Load LangChain objects from JSON strings or objects.\n *\n * ## How it works\n *\n * Each `Serializable` LangChain object has a unique identifier (its \"class path\"),\n * which is a list of strings representing the module path and class name. For example:\n *\n * - `AIMessage` -> `[\"langchain_core\", \"messages\", \"ai\", \"AIMessage\"]`\n * - `ChatPromptTemplate` -> `[\"langchain_core\", \"prompts\", \"chat\", \"ChatPromptTemplate\"]`\n *\n * When deserializing, the class path is validated against supported namespaces.\n *\n * ## Security model\n *\n * The `secretsFromEnv` parameter controls whether secrets can be loaded from environment\n * variables:\n *\n * - `false` (default): Secrets must be provided in `secretsMap`. If a secret is not\n * found, `null` is returned instead of loading from environment variables.\n * - `true`: If a secret is not found in `secretsMap`, it will be loaded from\n * environment variables. Use this only in trusted environments.\n *\n * ### Injection protection (escape-based)\n *\n * During serialization, plain objects that contain an `'lc'` key are escaped by wrapping\n * them: `{\"__lc_escaped__\": {...}}`. During deserialization, escaped objects are unwrapped\n * and returned as plain objects, NOT instantiated as LC objects.\n *\n * This is an allowlist approach: only objects explicitly produced by\n * `Serializable.toJSON()` (which are NOT escaped) are treated as LC objects;\n * everything else is user data.\n *\n * @module\n */\n\nimport {\n Serializable,\n SerializedConstructor,\n SerializedNotImplemented,\n SerializedSecret,\n get_lc_unique_name,\n} from \"./serializable.js\";\nimport { optionalImportEntrypoints as defaultOptionalImportEntrypoints } from \"./import_constants.js\";\nimport * as coreImportMap from \"./import_map.js\";\nimport type { OptionalImportMap, SecretMap } from \"./import_type.js\";\nimport { type SerializedFields, keyFromJson, mapKeys } from \"./map_keys.js\";\nimport { getEnvironmentVariable } from \"../utils/env.js\";\nimport { isEscapedObject, unescapeValue } from \"./validation.js\";\n\n/**\n * Options for loading serialized LangChain objects.\n *\n * @remarks\n * **Security considerations:**\n *\n * Deserialization can instantiate arbitrary classes from the allowed namespaces.\n * When loading untrusted data, be aware that:\n *\n * 1. **`secretsFromEnv`**: Defaults to `false`. Setting to `true` allows the\n * deserializer to read environment variables, which could leak secrets if\n * the serialized data contains malicious secret references.\n *\n * 2. **`importMap` / `optionalImportsMap`**: These allow extending which classes\n * can be instantiated. Never populate these from user input. Only include\n * modules you explicitly trust.\n *\n * 3. **Class instantiation**: Allowed classes will have their constructors called\n * with the deserialized kwargs. If a class performs side effects in its\n * constructor (network calls, file I/O, etc.), those will execute.\n */\nexport interface LoadOptions {\n /**\n * A map of secrets to load. Keys are secret identifiers, values are the secret values.\n *\n * If a secret is not found in this map and `secretsFromEnv` is `false`, an error is\n * thrown. If `secretsFromEnv` is `true`, the secret will be loaded from environment\n * variables (if not found there either, an error is thrown).\n */\n secretsMap?: SecretMap;\n\n /**\n * Whether to load secrets from environment variables when not found in `secretsMap`.\n *\n * @default false\n *\n * @remarks\n * **Security warning:** Setting this to `true` allows the deserializer to read\n * environment variables, which could be a security risk if the serialized data\n * is not trusted. Only set this to `true` when deserializing data from trusted\n * sources (e.g., your own database, not user input).\n */\n secretsFromEnv?: boolean;\n\n /**\n * A map of optional imports. Keys are namespace paths (e.g., \"langchain_community/llms\"),\n * values are the imported modules.\n *\n * @remarks\n * **Security warning:** This extends which classes can be instantiated during\n * deserialization. Never populate this map with values derived from user input.\n * Only include modules that you explicitly trust and have reviewed.\n *\n * Classes in these modules can be instantiated with attacker-controlled kwargs\n * if the serialized data is untrusted.\n */\n optionalImportsMap?: OptionalImportMap;\n\n /**\n * Additional optional import entrypoints to allow beyond the defaults.\n *\n * @remarks\n * **Security warning:** This extends which namespace paths are considered valid\n * for deserialization. Never populate this array with values derived from user\n * input. Each entrypoint you add expands the attack surface for deserialization.\n */\n optionalImportEntrypoints?: string[];\n\n /**\n * Additional import map for the \"langchain\" namespace.\n *\n * @remarks\n * **Security warning:** This extends which classes can be instantiated during\n * deserialization. Never populate this map with values derived from user input.\n * Only include modules that you explicitly trust and have reviewed.\n *\n * Any class exposed through this map can be instantiated with attacker-controlled\n * kwargs if the serialized data is untrusted.\n */\n importMap?: Record<string, unknown>;\n\n /**\n * Maximum recursion depth allowed during deserialization.\n *\n * @default 50\n *\n * @remarks\n * This limit protects against denial-of-service attacks using deeply nested\n * JSON structures that could cause stack overflow. If your legitimate data\n * requires deeper nesting, you can increase this limit.\n */\n maxDepth?: number;\n}\n\n/**\n * Default maximum recursion depth for deserialization.\n * This provides protection against DoS attacks via deeply nested structures.\n */\nconst DEFAULT_MAX_DEPTH = 50;\n\nfunction combineAliasesAndInvert(constructor: typeof Serializable) {\n const aliases: { [key: string]: string } = {};\n for (\n let current = constructor;\n current && current.prototype;\n current = Object.getPrototypeOf(current)\n ) {\n Object.assign(aliases, Reflect.get(current.prototype, \"lc_aliases\"));\n }\n return Object.entries(aliases).reduce((acc, [key, value]) => {\n acc[value] = key;\n return acc;\n }, {} as Record<string, string>);\n}\n\ninterface ReviverContext {\n optionalImportsMap: OptionalImportMap;\n optionalImportEntrypoints: string[];\n secretsMap: SecretMap;\n secretsFromEnv: boolean;\n importMap: Record<string, unknown>;\n path: string[];\n depth: number;\n maxDepth: number;\n}\n\n/**\n * Recursively revive a value, handling escape markers and LC objects.\n *\n * This function handles:\n * 1. Escaped dicts - unwrapped and returned as plain objects\n * 2. LC secret objects - resolved from secretsMap or env\n * 3. LC constructor objects - instantiated\n * 4. Regular objects/arrays - recursed into\n */\nasync function reviver(this: ReviverContext, value: unknown): Promise<unknown> {\n const {\n optionalImportsMap,\n optionalImportEntrypoints,\n importMap,\n secretsMap,\n secretsFromEnv,\n path,\n depth,\n maxDepth,\n } = this;\n const pathStr = path.join(\".\");\n\n // Check recursion depth to prevent DoS via deeply nested structures\n if (depth > maxDepth) {\n throw new Error(\n `Maximum recursion depth (${maxDepth}) exceeded during deserialization. ` +\n `This may indicate a malicious payload or you may need to increase maxDepth.`\n );\n }\n\n // If not an object, return as-is\n if (typeof value !== \"object\" || value == null) {\n return value;\n }\n\n // Handle arrays - recurse into elements\n if (Array.isArray(value)) {\n return Promise.all(\n value.map((v, i) =>\n reviver.call({ ...this, path: [...path, `${i}`], depth: depth + 1 }, v)\n )\n );\n }\n\n // It's an object - check for escape marker FIRST\n const record = value as Record<string, unknown>;\n if (isEscapedObject(record)) {\n // This is an escaped user object - unwrap and return as-is (no LC processing)\n return unescapeValue(record);\n }\n\n // Check for LC secret object\n if (\n \"lc\" in record &&\n \"type\" in record &&\n \"id\" in record &&\n record.lc === 1 &&\n record.type === \"secret\"\n ) {\n const serialized = record as unknown as SerializedSecret;\n const [key] = serialized.id;\n if (key in secretsMap) {\n return secretsMap[key as keyof SecretMap];\n } else if (secretsFromEnv) {\n const secretValueInEnv = getEnvironmentVariable(key);\n if (secretValueInEnv) {\n return secretValueInEnv;\n }\n }\n throw new Error(`Missing secret \"${key}\" at ${pathStr}`);\n }\n\n // Check for LC not_implemented object\n if (\n \"lc\" in record &&\n \"type\" in record &&\n \"id\" in record &&\n record.lc === 1 &&\n record.type === \"not_implemented\"\n ) {\n const serialized = record as unknown as SerializedNotImplemented;\n const str = JSON.stringify(serialized);\n throw new Error(\n `Trying to load an object that doesn't implement serialization: ${pathStr} -> ${str}`\n );\n }\n\n // Check for LC constructor object\n if (\n \"lc\" in record &&\n \"type\" in record &&\n \"id\" in record &&\n \"kwargs\" in record &&\n record.lc === 1 &&\n record.type === \"constructor\"\n ) {\n const serialized = record as unknown as SerializedConstructor;\n const str = JSON.stringify(serialized);\n const [name, ...namespaceReverse] = serialized.id.slice().reverse();\n const namespace = namespaceReverse.reverse();\n const importMaps = { langchain_core: coreImportMap, langchain: importMap };\n\n let module:\n | (typeof importMaps)[\"langchain_core\"][keyof (typeof importMaps)[\"langchain_core\"]]\n | (typeof importMaps)[\"langchain\"][keyof (typeof importMaps)[\"langchain\"]]\n | OptionalImportMap[keyof OptionalImportMap]\n | null = null;\n\n const optionalImportNamespaceAliases = [namespace.join(\"/\")];\n if (namespace[0] === \"langchain_community\") {\n optionalImportNamespaceAliases.push(\n [\"langchain\", ...namespace.slice(1)].join(\"/\")\n );\n }\n const matchingNamespaceAlias = optionalImportNamespaceAliases.find(\n (alias) => alias in optionalImportsMap\n );\n if (\n defaultOptionalImportEntrypoints\n .concat(optionalImportEntrypoints)\n .includes(namespace.join(\"/\")) ||\n matchingNamespaceAlias\n ) {\n if (matchingNamespaceAlias !== undefined) {\n module = await optionalImportsMap[\n matchingNamespaceAlias as keyof typeof optionalImportsMap\n ];\n } else {\n throw new Error(\n `Missing key \"${namespace.join(\n \"/\"\n )}\" for ${pathStr} in load(optionalImportsMap={})`\n );\n }\n } else {\n let finalImportMap:\n | (typeof importMaps)[\"langchain\"]\n | (typeof importMaps)[\"langchain_core\"];\n // Currently, we only support langchain and langchain_core imports.\n if (namespace[0] === \"langchain\" || namespace[0] === \"langchain_core\") {\n finalImportMap = importMaps[namespace[0]];\n namespace.shift();\n } else {\n throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);\n }\n\n // The root namespace \"langchain\" is not a valid import.\n if (namespace.length === 0) {\n throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);\n }\n\n // Find the longest matching namespace.\n let importMapKey: string;\n do {\n importMapKey = namespace.join(\"__\");\n if (importMapKey in finalImportMap) {\n break;\n } else {\n namespace.pop();\n }\n } while (namespace.length > 0);\n\n // If no matching namespace is found, throw an error.\n if (importMapKey in finalImportMap) {\n module = finalImportMap[importMapKey as keyof typeof finalImportMap];\n }\n }\n\n if (typeof module !== \"object\" || module === null) {\n throw new Error(`Invalid namespace: ${pathStr} -> ${str}`);\n }\n\n // Extract the builder from the import map.\n const builder =\n // look for a named export with the same name as the class\n module[name as keyof typeof module] ??\n // look for an export with a lc_name property matching the class name\n // this is necessary for classes that are minified\n Object.values(module).find(\n (v) =>\n typeof v === \"function\" &&\n get_lc_unique_name(v as typeof Serializable) === name\n );\n if (typeof builder !== \"function\") {\n throw new Error(`Invalid identifer: ${pathStr} -> ${str}`);\n }\n\n // Recurse on the arguments, which may be serialized objects themselves\n const kwargs = await reviver.call(\n { ...this, path: [...path, \"kwargs\"], depth: depth + 1 },\n serialized.kwargs\n );\n\n // Construct the object\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const instance = new (builder as any)(\n mapKeys(\n kwargs as SerializedFields,\n keyFromJson,\n combineAliasesAndInvert(builder)\n )\n );\n\n // Minification in severless/edge runtimes will mange the\n // name of classes presented in traces. As the names in import map\n // are present as-is even with minification, use these names instead\n Object.defineProperty(instance.constructor, \"name\", { value: name });\n\n return instance;\n }\n\n // Regular object - recurse into values\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(record)) {\n result[key] = await reviver.call(\n { ...this, path: [...path, key], depth: depth + 1 },\n val\n );\n }\n return result;\n}\n\n/**\n * Load a LangChain object from a JSON string.\n *\n * @param text - The JSON string to parse and load.\n * @param options - Options for loading.\n * @returns The loaded LangChain object.\n *\n * @example\n * ```typescript\n * import { load } from \"@langchain/core/load\";\n * import { AIMessage } from \"@langchain/core/messages\";\n *\n * // Basic usage - secrets must be provided explicitly\n * const msg = await load<AIMessage>(jsonString);\n *\n * // With secrets from a map\n * const msg = await load<AIMessage>(jsonString, {\n * secretsMap: { OPENAI_API_KEY: \"sk-...\" }\n * });\n *\n * // Allow loading secrets from environment (use with caution)\n * const msg = await load<AIMessage>(jsonString, {\n * secretsFromEnv: true\n * });\n * ```\n */\nexport async function load<T>(text: string, options?: LoadOptions): Promise<T> {\n const json = JSON.parse(text);\n\n const context: ReviverContext = {\n optionalImportsMap: options?.optionalImportsMap ?? {},\n optionalImportEntrypoints: options?.optionalImportEntrypoints ?? [],\n secretsMap: options?.secretsMap ?? {},\n secretsFromEnv: options?.secretsFromEnv ?? false,\n importMap: options?.importMap ?? {},\n path: [\"$\"],\n depth: 0,\n maxDepth: options?.maxDepth ?? DEFAULT_MAX_DEPTH,\n };\n\n return reviver.call(context, json) as Promise<T>;\n}\n"],"mappings":";;;;;;;;;;;;AAoJA,MAAM,oBAAoB;AAE1B,SAAS,wBAAwBA,aAAkC;CACjE,MAAMC,UAAqC,CAAE;AAC7C,MACE,IAAI,UAAU,aACd,WAAW,QAAQ,WACnB,UAAU,OAAO,eAAe,QAAQ,EAExC,OAAO,OAAO,SAAS,QAAQ,IAAI,QAAQ,WAAW,aAAa,CAAC;AAEtE,QAAO,OAAO,QAAQ,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,MAAM,KAAK;EAC3D,IAAI,SAAS;AACb,SAAO;CACR,GAAE,CAAE,EAA2B;AACjC;;;;;;;;;;AAsBD,eAAe,QAA8BC,OAAkC;CAC7E,MAAM,EACJ,oBACA,wDACA,WACA,YACA,gBACA,MACA,OACA,UACD,GAAG;CACJ,MAAM,UAAU,KAAK,KAAK,IAAI;AAG9B,KAAI,QAAQ,SACV,OAAM,IAAI,MACR,CAAC,yBAAyB,EAAE,SAAS,8GAAmC,CACO;AAKnF,KA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AAM,CAAC,GAAG,MAAM,QAAS;GAAE,OAAO,QAAQ;EAAG,GACxD,WAAW,OACZ;EAID,MAAM,WAAW,IAAK,QACpBC,yBACE,QACAC,8BACA,wBAAwB,QAAQ,CACjC;EAMH,OAAO,eAAe,SAAS,aAAa,QAAQ,EAAE,OAAO,KAAM,EAAC;AAEpE,SAAO;CACR;CAGD,MAAMC,SAAkC,CAAE;AAC1C,MAAK,MAAM,CAAC,KAAK,IAAI,IAAI,OAAO,QAAQ,OAAO,EAC7C,OAAO,OAAO,MAAM,QAAQ,KAC1B;EAAE,GAAG;EAAM,MAAM,CAAC,GAAG,MAAM,GAAI;EAAE,OAAO,QAAQ;CAAG,GACnD,IACD;AAEH,QAAO;AACR;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BD,eAAsB,KAAQC,MAAcC,SAAmC;CAC7E,MAAM,OAAO,KAAK,MAAM,KAAK;CAE7B,MAAMC,UAA0B;EAC9B,oBAAoB,SAAS,sBAAsB,CAAE;EACrD,2BAA2B,SAAS,6BAA6B,CAAE;EACnE,YAAY,SAAS,cAAc,CAAE;EACrC,gBAAgB,SAAS,kBAAkB;EAC3C,WAAW,SAAS,aAAa,CAAE;EACnC,MAAM,CAAC,GAAI;EACX,OAAO;EACP,UAAU,SAAS,YAAY;CAChC;AAED,QAAO,QAAQ,KAAK,SAAS,KAAK;AACnC"}
@@ -1,12 +1,122 @@
1
1
  import { OptionalImportMap, SecretMap } from "./import_type.cjs";
2
2
 
3
3
  //#region src/load/index.d.ts
4
- declare function load<T>(text: string, mappings?: {
4
+
5
+ /**
6
+ * Options for loading serialized LangChain objects.
7
+ *
8
+ * @remarks
9
+ * **Security considerations:**
10
+ *
11
+ * Deserialization can instantiate arbitrary classes from the allowed namespaces.
12
+ * When loading untrusted data, be aware that:
13
+ *
14
+ * 1. **`secretsFromEnv`**: Defaults to `false`. Setting to `true` allows the
15
+ * deserializer to read environment variables, which could leak secrets if
16
+ * the serialized data contains malicious secret references.
17
+ *
18
+ * 2. **`importMap` / `optionalImportsMap`**: These allow extending which classes
19
+ * can be instantiated. Never populate these from user input. Only include
20
+ * modules you explicitly trust.
21
+ *
22
+ * 3. **Class instantiation**: Allowed classes will have their constructors called
23
+ * with the deserialized kwargs. If a class performs side effects in its
24
+ * constructor (network calls, file I/O, etc.), those will execute.
25
+ */
26
+ interface LoadOptions {
27
+ /**
28
+ * A map of secrets to load. Keys are secret identifiers, values are the secret values.
29
+ *
30
+ * If a secret is not found in this map and `secretsFromEnv` is `false`, an error is
31
+ * thrown. If `secretsFromEnv` is `true`, the secret will be loaded from environment
32
+ * variables (if not found there either, an error is thrown).
33
+ */
5
34
  secretsMap?: SecretMap;
35
+ /**
36
+ * Whether to load secrets from environment variables when not found in `secretsMap`.
37
+ *
38
+ * @default false
39
+ *
40
+ * @remarks
41
+ * **Security warning:** Setting this to `true` allows the deserializer to read
42
+ * environment variables, which could be a security risk if the serialized data
43
+ * is not trusted. Only set this to `true` when deserializing data from trusted
44
+ * sources (e.g., your own database, not user input).
45
+ */
46
+ secretsFromEnv?: boolean;
47
+ /**
48
+ * A map of optional imports. Keys are namespace paths (e.g., "langchain_community/llms"),
49
+ * values are the imported modules.
50
+ *
51
+ * @remarks
52
+ * **Security warning:** This extends which classes can be instantiated during
53
+ * deserialization. Never populate this map with values derived from user input.
54
+ * Only include modules that you explicitly trust and have reviewed.
55
+ *
56
+ * Classes in these modules can be instantiated with attacker-controlled kwargs
57
+ * if the serialized data is untrusted.
58
+ */
6
59
  optionalImportsMap?: OptionalImportMap;
60
+ /**
61
+ * Additional optional import entrypoints to allow beyond the defaults.
62
+ *
63
+ * @remarks
64
+ * **Security warning:** This extends which namespace paths are considered valid
65
+ * for deserialization. Never populate this array with values derived from user
66
+ * input. Each entrypoint you add expands the attack surface for deserialization.
67
+ */
7
68
  optionalImportEntrypoints?: string[];
69
+ /**
70
+ * Additional import map for the "langchain" namespace.
71
+ *
72
+ * @remarks
73
+ * **Security warning:** This extends which classes can be instantiated during
74
+ * deserialization. Never populate this map with values derived from user input.
75
+ * Only include modules that you explicitly trust and have reviewed.
76
+ *
77
+ * Any class exposed through this map can be instantiated with attacker-controlled
78
+ * kwargs if the serialized data is untrusted.
79
+ */
8
80
  importMap?: Record<string, unknown>;
9
- }): Promise<T>;
81
+ /**
82
+ * Maximum recursion depth allowed during deserialization.
83
+ *
84
+ * @default 50
85
+ *
86
+ * @remarks
87
+ * This limit protects against denial-of-service attacks using deeply nested
88
+ * JSON structures that could cause stack overflow. If your legitimate data
89
+ * requires deeper nesting, you can increase this limit.
90
+ */
91
+ maxDepth?: number;
92
+ }
93
+ /**
94
+ * Load a LangChain object from a JSON string.
95
+ *
96
+ * @param text - The JSON string to parse and load.
97
+ * @param options - Options for loading.
98
+ * @returns The loaded LangChain object.
99
+ *
100
+ * @example
101
+ * ```typescript
102
+ * import { load } from "@langchain/core/load";
103
+ * import { AIMessage } from "@langchain/core/messages";
104
+ *
105
+ * // Basic usage - secrets must be provided explicitly
106
+ * const msg = await load<AIMessage>(jsonString);
107
+ *
108
+ * // With secrets from a map
109
+ * const msg = await load<AIMessage>(jsonString, {
110
+ * secretsMap: { OPENAI_API_KEY: "sk-..." }
111
+ * });
112
+ *
113
+ * // Allow loading secrets from environment (use with caution)
114
+ * const msg = await load<AIMessage>(jsonString, {
115
+ * secretsFromEnv: true
116
+ * });
117
+ * ```
118
+ */
119
+ declare function load<T>(text: string, options?: LoadOptions): Promise<T>;
10
120
  //#endregion
11
- export { load };
121
+ export { LoadOptions, load };
12
122
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":["OptionalImportMap","SecretMap","load","T","Record","Promise"],"sources":["../../src/load/index.d.ts"],"sourcesContent":["import type { OptionalImportMap, SecretMap } from \"./import_type.js\";\nexport declare function load<T>(text: string, mappings?: {\n secretsMap?: SecretMap;\n optionalImportsMap?: OptionalImportMap;\n optionalImportEntrypoints?: string[];\n importMap?: Record<string, unknown>;\n}): Promise<T>;\n//# sourceMappingURL=index.d.ts.map"],"mappings":";;;iBACwBE,8BAIRE;eAHCH;EADOC,kBAAIC,CAAAA,EAEHH,iBAFG;EACXC,yBAAAA,CAAAA,EAAAA,MAAAA,EAAAA;EACQD,SAAAA,CAAAA,EAETI,MAFSJ,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;CAETI,CAAAA,EACZC,OADYD,CACJD,CADIC,CAAAA"}
1
+ {"version":3,"file":"index.d.cts","names":["OptionalImportMap","SecretMap","LoadOptions","Record","load","T","Promise"],"sources":["../../src/load/index.d.ts"],"sourcesContent":["/**\n * Load LangChain objects from JSON strings or objects.\n *\n * ## How it works\n *\n * Each `Serializable` LangChain object has a unique identifier (its \"class path\"),\n * which is a list of strings representing the module path and class name. For example:\n *\n * - `AIMessage` -> `[\"langchain_core\", \"messages\", \"ai\", \"AIMessage\"]`\n * - `ChatPromptTemplate` -> `[\"langchain_core\", \"prompts\", \"chat\", \"ChatPromptTemplate\"]`\n *\n * When deserializing, the class path is validated against supported namespaces.\n *\n * ## Security model\n *\n * The `secretsFromEnv` parameter controls whether secrets can be loaded from environment\n * variables:\n *\n * - `false` (default): Secrets must be provided in `secretsMap`. If a secret is not\n * found, `null` is returned instead of loading from environment variables.\n * - `true`: If a secret is not found in `secretsMap`, it will be loaded from\n * environment variables. Use this only in trusted environments.\n *\n * ### Injection protection (escape-based)\n *\n * During serialization, plain objects that contain an `'lc'` key are escaped by wrapping\n * them: `{\"__lc_escaped__\": {...}}`. During deserialization, escaped objects are unwrapped\n * and returned as plain objects, NOT instantiated as LC objects.\n *\n * This is an allowlist approach: only objects explicitly produced by\n * `Serializable.toJSON()` (which are NOT escaped) are treated as LC objects;\n * everything else is user data.\n *\n * @module\n */\nimport type { OptionalImportMap, SecretMap } from \"./import_type.js\";\n/**\n * Options for loading serialized LangChain objects.\n *\n * @remarks\n * **Security considerations:**\n *\n * Deserialization can instantiate arbitrary classes from the allowed namespaces.\n * When loading untrusted data, be aware that:\n *\n * 1. **`secretsFromEnv`**: Defaults to `false`. Setting to `true` allows the\n * deserializer to read environment variables, which could leak secrets if\n * the serialized data contains malicious secret references.\n *\n * 2. **`importMap` / `optionalImportsMap`**: These allow extending which classes\n * can be instantiated. Never populate these from user input. Only include\n * modules you explicitly trust.\n *\n * 3. **Class instantiation**: Allowed classes will have their constructors called\n * with the deserialized kwargs. If a class performs side effects in its\n * constructor (network calls, file I/O, etc.), those will execute.\n */\nexport interface LoadOptions {\n /**\n * A map of secrets to load. Keys are secret identifiers, values are the secret values.\n *\n * If a secret is not found in this map and `secretsFromEnv` is `false`, an error is\n * thrown. If `secretsFromEnv` is `true`, the secret will be loaded from environment\n * variables (if not found there either, an error is thrown).\n */\n secretsMap?: SecretMap;\n /**\n * Whether to load secrets from environment variables when not found in `secretsMap`.\n *\n * @default false\n *\n * @remarks\n * **Security warning:** Setting this to `true` allows the deserializer to read\n * environment variables, which could be a security risk if the serialized data\n * is not trusted. Only set this to `true` when deserializing data from trusted\n * sources (e.g., your own database, not user input).\n */\n secretsFromEnv?: boolean;\n /**\n * A map of optional imports. Keys are namespace paths (e.g., \"langchain_community/llms\"),\n * values are the imported modules.\n *\n * @remarks\n * **Security warning:** This extends which classes can be instantiated during\n * deserialization. Never populate this map with values derived from user input.\n * Only include modules that you explicitly trust and have reviewed.\n *\n * Classes in these modules can be instantiated with attacker-controlled kwargs\n * if the serialized data is untrusted.\n */\n optionalImportsMap?: OptionalImportMap;\n /**\n * Additional optional import entrypoints to allow beyond the defaults.\n *\n * @remarks\n * **Security warning:** This extends which namespace paths are considered valid\n * for deserialization. Never populate this array with values derived from user\n * input. Each entrypoint you add expands the attack surface for deserialization.\n */\n optionalImportEntrypoints?: string[];\n /**\n * Additional import map for the \"langchain\" namespace.\n *\n * @remarks\n * **Security warning:** This extends which classes can be instantiated during\n * deserialization. Never populate this map with values derived from user input.\n * Only include modules that you explicitly trust and have reviewed.\n *\n * Any class exposed through this map can be instantiated with attacker-controlled\n * kwargs if the serialized data is untrusted.\n */\n importMap?: Record<string, unknown>;\n /**\n * Maximum recursion depth allowed during deserialization.\n *\n * @default 50\n *\n * @remarks\n * This limit protects against denial-of-service attacks using deeply nested\n * JSON structures that could cause stack overflow. If your legitimate data\n * requires deeper nesting, you can increase this limit.\n */\n maxDepth?: number;\n}\n/**\n * Load a LangChain object from a JSON string.\n *\n * @param text - The JSON string to parse and load.\n * @param options - Options for loading.\n * @returns The loaded LangChain object.\n *\n * @example\n * ```typescript\n * import { load } from \"@langchain/core/load\";\n * import { AIMessage } from \"@langchain/core/messages\";\n *\n * // Basic usage - secrets must be provided explicitly\n * const msg = await load<AIMessage>(jsonString);\n *\n * // With secrets from a map\n * const msg = await load<AIMessage>(jsonString, {\n * secretsMap: { OPENAI_API_KEY: \"sk-...\" }\n * });\n *\n * // Allow loading secrets from environment (use with caution)\n * const msg = await load<AIMessage>(jsonString, {\n * secretsFromEnv: true\n * });\n * ```\n */\nexport declare function load<T>(text: string, options?: LoadOptions): Promise<T>;\n//# sourceMappingURL=index.d.ts.map"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;UAyDiBE,WAAAA;;;;;;;;eAQAD;;;;;;;;;;;;;;;;;;;;;;;;;uBAyBQD;;;;;;;;;;;;;;;;;;;;;cAqBTG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAuCQC,gCAAgCF,cAAcI,QAAQD"}