@langchain/core 1.2.9 → 1.2.10

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 (167) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/_virtual/_rolldown/runtime.cjs +1 -1
  3. package/dist/callbacks/dispatch/index.cjs +2 -1
  4. package/dist/callbacks/dispatch/index.cjs.map +1 -1
  5. package/dist/callbacks/dispatch/index.js +2 -1
  6. package/dist/callbacks/dispatch/index.js.map +1 -1
  7. package/dist/indexing/base.cjs +10 -6
  8. package/dist/indexing/base.cjs.map +1 -1
  9. package/dist/indexing/base.js +10 -6
  10. package/dist/indexing/base.js.map +1 -1
  11. package/dist/language_models/base.cjs +1 -1
  12. package/dist/language_models/base.cjs.map +1 -1
  13. package/dist/language_models/base.js +1 -1
  14. package/dist/language_models/base.js.map +1 -1
  15. package/dist/language_models/chat_models.cjs +10 -5
  16. package/dist/language_models/chat_models.cjs.map +1 -1
  17. package/dist/language_models/chat_models.js +10 -5
  18. package/dist/language_models/chat_models.js.map +1 -1
  19. package/dist/language_models/stream.cjs +0 -2
  20. package/dist/language_models/stream.cjs.map +1 -1
  21. package/dist/language_models/stream.js +0 -2
  22. package/dist/language_models/stream.js.map +1 -1
  23. package/dist/load/index.cjs +7 -5
  24. package/dist/load/index.cjs.map +1 -1
  25. package/dist/load/index.js +7 -5
  26. package/dist/load/index.js.map +1 -1
  27. package/dist/load/serializable.cjs +2 -1
  28. package/dist/load/serializable.cjs.map +1 -1
  29. package/dist/load/serializable.js +2 -1
  30. package/dist/load/serializable.js.map +1 -1
  31. package/dist/load/validation.cjs +4 -3
  32. package/dist/load/validation.cjs.map +1 -1
  33. package/dist/load/validation.js +4 -3
  34. package/dist/load/validation.js.map +1 -1
  35. package/dist/messages/base.cjs +13 -18
  36. package/dist/messages/base.cjs.map +1 -1
  37. package/dist/messages/base.d.cts.map +1 -1
  38. package/dist/messages/base.d.ts.map +1 -1
  39. package/dist/messages/base.js +13 -18
  40. package/dist/messages/base.js.map +1 -1
  41. package/dist/messages/block_translators/anthropic.cjs.map +1 -1
  42. package/dist/messages/block_translators/anthropic.js.map +1 -1
  43. package/dist/messages/block_translators/google.cjs +10 -9
  44. package/dist/messages/block_translators/google.cjs.map +1 -1
  45. package/dist/messages/block_translators/google.js +10 -9
  46. package/dist/messages/block_translators/google.js.map +1 -1
  47. package/dist/messages/block_translators/google_vertexai.cjs +14 -12
  48. package/dist/messages/block_translators/google_vertexai.cjs.map +1 -1
  49. package/dist/messages/block_translators/google_vertexai.js +14 -12
  50. package/dist/messages/block_translators/google_vertexai.js.map +1 -1
  51. package/dist/messages/message.cjs.map +1 -1
  52. package/dist/messages/message.d.cts.map +1 -1
  53. package/dist/messages/message.d.ts.map +1 -1
  54. package/dist/messages/message.js.map +1 -1
  55. package/dist/messages/transformers.cjs +12 -8
  56. package/dist/messages/transformers.cjs.map +1 -1
  57. package/dist/messages/transformers.js +12 -8
  58. package/dist/messages/transformers.js.map +1 -1
  59. package/dist/output_parsers/transform.cjs.map +1 -1
  60. package/dist/prompts/chat.cjs +2 -1
  61. package/dist/prompts/chat.cjs.map +1 -1
  62. package/dist/prompts/chat.js +2 -1
  63. package/dist/prompts/chat.js.map +1 -1
  64. package/dist/prompts/few_shot.cjs +6 -4
  65. package/dist/prompts/few_shot.cjs.map +1 -1
  66. package/dist/prompts/few_shot.js +6 -4
  67. package/dist/prompts/few_shot.js.map +1 -1
  68. package/dist/prompts/image.cjs +2 -1
  69. package/dist/prompts/image.cjs.map +1 -1
  70. package/dist/prompts/image.js +2 -1
  71. package/dist/prompts/image.js.map +1 -1
  72. package/dist/prompts/prompt.cjs.map +1 -1
  73. package/dist/prompts/prompt.d.cts.map +1 -1
  74. package/dist/prompts/prompt.d.ts.map +1 -1
  75. package/dist/prompts/prompt.js.map +1 -1
  76. package/dist/prompts/string.cjs +2 -1
  77. package/dist/prompts/string.cjs.map +1 -1
  78. package/dist/prompts/string.js +2 -1
  79. package/dist/prompts/string.js.map +1 -1
  80. package/dist/prompts/template.cjs.map +1 -1
  81. package/dist/prompts/template.js.map +1 -1
  82. package/dist/runnables/base.cjs +60 -40
  83. package/dist/runnables/base.cjs.map +1 -1
  84. package/dist/runnables/base.js +60 -40
  85. package/dist/runnables/base.js.map +1 -1
  86. package/dist/runnables/branch.cjs +16 -12
  87. package/dist/runnables/branch.cjs.map +1 -1
  88. package/dist/runnables/branch.js +16 -12
  89. package/dist/runnables/branch.js.map +1 -1
  90. package/dist/runnables/config.cjs +28 -23
  91. package/dist/runnables/config.cjs.map +1 -1
  92. package/dist/runnables/config.js +28 -23
  93. package/dist/runnables/config.js.map +1 -1
  94. package/dist/runnables/graph.cjs +2 -1
  95. package/dist/runnables/graph.cjs.map +1 -1
  96. package/dist/runnables/graph.js +2 -1
  97. package/dist/runnables/graph.js.map +1 -1
  98. package/dist/runnables/passthrough.cjs +8 -6
  99. package/dist/runnables/passthrough.cjs.map +1 -1
  100. package/dist/runnables/passthrough.js +8 -6
  101. package/dist/runnables/passthrough.js.map +1 -1
  102. package/dist/singletons/async_local_storage/context.cjs.map +1 -1
  103. package/dist/singletons/tracer.cjs +4 -1
  104. package/dist/singletons/tracer.cjs.map +1 -1
  105. package/dist/singletons/tracer.js +4 -1
  106. package/dist/singletons/tracer.js.map +1 -1
  107. package/dist/tools/index.cjs +22 -20
  108. package/dist/tools/index.cjs.map +1 -1
  109. package/dist/tools/index.js +22 -20
  110. package/dist/tools/index.js.map +1 -1
  111. package/dist/tracers/base.cjs +11 -10
  112. package/dist/tracers/base.cjs.map +1 -1
  113. package/dist/tracers/base.js +11 -10
  114. package/dist/tracers/base.js.map +1 -1
  115. package/dist/tracers/log_stream.cjs +7 -6
  116. package/dist/tracers/log_stream.cjs.map +1 -1
  117. package/dist/tracers/log_stream.js +7 -6
  118. package/dist/tracers/log_stream.js.map +1 -1
  119. package/dist/tracers/tracer_langchain.cjs.map +1 -1
  120. package/dist/utils/env.cjs.map +1 -1
  121. package/dist/utils/env.d.cts.map +1 -1
  122. package/dist/utils/env.d.ts.map +1 -1
  123. package/dist/utils/env.js.map +1 -1
  124. package/dist/utils/event_source_parse.cjs +1 -3
  125. package/dist/utils/event_source_parse.cjs.map +1 -1
  126. package/dist/utils/event_source_parse.js +1 -3
  127. package/dist/utils/event_source_parse.js.map +1 -1
  128. package/dist/utils/fast-json-patch/src/core.cjs +4 -2
  129. package/dist/utils/fast-json-patch/src/core.cjs.map +1 -1
  130. package/dist/utils/fast-json-patch/src/core.js +4 -2
  131. package/dist/utils/fast-json-patch/src/core.js.map +1 -1
  132. package/dist/utils/fast-json-patch/src/helpers.cjs.map +1 -1
  133. package/dist/utils/fast-json-patch/src/helpers.js.map +1 -1
  134. package/dist/utils/js-sha256/hash.cjs.map +1 -1
  135. package/dist/utils/js-sha256/hash.js.map +1 -1
  136. package/dist/utils/json_schema.cjs +4 -2
  137. package/dist/utils/json_schema.cjs.map +1 -1
  138. package/dist/utils/json_schema.js +4 -2
  139. package/dist/utils/json_schema.js.map +1 -1
  140. package/dist/utils/sax-js/sax.cjs +41 -35
  141. package/dist/utils/sax-js/sax.cjs.map +1 -1
  142. package/dist/utils/sax-js/sax.js +41 -35
  143. package/dist/utils/sax-js/sax.js.map +1 -1
  144. package/dist/utils/testing/chat_models.cjs +2 -1
  145. package/dist/utils/testing/chat_models.cjs.map +1 -1
  146. package/dist/utils/testing/chat_models.js +2 -1
  147. package/dist/utils/testing/chat_models.js.map +1 -1
  148. package/dist/utils/tiktoken.cjs.map +1 -1
  149. package/dist/utils/types/zod.cjs.map +1 -1
  150. package/dist/utils/types/zod.js.map +1 -1
  151. package/dist/utils/zod-to-json-schema/parsers/bigint.cjs +9 -9
  152. package/dist/utils/zod-to-json-schema/parsers/bigint.cjs.map +1 -1
  153. package/dist/utils/zod-to-json-schema/parsers/bigint.js +9 -9
  154. package/dist/utils/zod-to-json-schema/parsers/bigint.js.map +1 -1
  155. package/dist/utils/zod-to-json-schema/parsers/date.cjs +1 -3
  156. package/dist/utils/zod-to-json-schema/parsers/date.cjs.map +1 -1
  157. package/dist/utils/zod-to-json-schema/parsers/date.js +1 -3
  158. package/dist/utils/zod-to-json-schema/parsers/date.js.map +1 -1
  159. package/dist/utils/zod-to-json-schema/parsers/number.cjs +9 -9
  160. package/dist/utils/zod-to-json-schema/parsers/number.cjs.map +1 -1
  161. package/dist/utils/zod-to-json-schema/parsers/number.js +9 -9
  162. package/dist/utils/zod-to-json-schema/parsers/number.js.map +1 -1
  163. package/dist/utils/zod-to-json-schema/parsers/string.cjs +3 -13
  164. package/dist/utils/zod-to-json-schema/parsers/string.cjs.map +1 -1
  165. package/dist/utils/zod-to-json-schema/parsers/string.js +3 -13
  166. package/dist/utils/zod-to-json-schema/parsers/string.js.map +1 -1
  167. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"validation.cjs","names":[],"sources":["../../src/load/validation.ts"],"sourcesContent":["/**\n * Sentinel key used to mark escaped user objects during serialization.\n *\n * When a plain object contains 'lc' key (which could be confused with LC objects),\n * we wrap it as `{\"__lc_escaped__\": {...original...}}`.\n */\nexport const LC_ESCAPED_KEY = \"__lc_escaped__\";\n\n/**\n * Check if an object needs escaping to prevent confusion with LC objects.\n *\n * An object needs escaping if:\n * 1. It has an `'lc'` key (could be confused with LC serialization format)\n * 2. It has only the escape key (would be mistaken for an escaped object)\n */\nexport function needsEscaping(obj: Record<string, unknown>): boolean {\n return (\n \"lc\" in obj || (Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj)\n );\n}\n\n/**\n * Wrap an object in the escape marker.\n *\n * @example\n * ```typescript\n * {\"key\": \"value\"} // becomes {\"__lc_escaped__\": {\"key\": \"value\"}}\n * ```\n */\nexport function escapeObject(\n obj: Record<string, unknown>\n): Record<string, unknown> {\n return { [LC_ESCAPED_KEY]: obj };\n}\n\n/**\n * Check if an object is an escaped user object.\n *\n * @example\n * ```typescript\n * {\"__lc_escaped__\": {...}} // is an escaped object\n * ```\n */\nexport function isEscapedObject(obj: Record<string, unknown>): boolean {\n return Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj;\n}\n\n/**\n * Interface for objects that can be serialized.\n * This is a duck-typed interface to avoid circular imports.\n */\ninterface SerializableLike {\n lc_serializable: boolean;\n lc_secrets?: Record<string, string>;\n toJSON(): {\n lc: number;\n type: string;\n id: string[];\n kwargs?: Record<string, unknown>;\n };\n}\n\n/**\n * Check if an object looks like a Serializable instance (duck typing).\n */\nfunction isSerializableLike(obj: unknown): obj is SerializableLike {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"lc_serializable\" in obj &&\n typeof (obj as SerializableLike).toJSON === \"function\"\n );\n}\n\n/**\n * Create a \"not_implemented\" serialization result for objects that cannot be serialized.\n */\nfunction createNotImplemented(obj: unknown): {\n lc: 1;\n type: \"not_implemented\";\n id: string[];\n} {\n let id: string[];\n if (obj !== null && typeof obj === \"object\") {\n if (\"lc_id\" in obj && Array.isArray(obj.lc_id)) {\n id = obj.lc_id as string[];\n } else {\n id = [obj.constructor?.name ?? \"Object\"];\n }\n } else {\n id = [typeof obj];\n }\n return {\n lc: 1,\n type: \"not_implemented\",\n id,\n };\n}\n\n/**\n * Serialize a value with escaping of user objects.\n *\n * Called recursively on kwarg values to escape any plain objects that could be\n * confused with LC objects.\n *\n * @param obj - The value to serialize.\n * @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references.\n * Objects are removed after processing to allow shared references (same object in\n * multiple places) while still detecting true circular references (ancestor in descendant).\n * @returns The serialized value with user objects escaped as needed.\n */\nexport function serializeValue(\n obj: unknown,\n pathSet: WeakSet<object> = new WeakSet()\n): unknown {\n if (obj !== null && typeof obj === \"object\" && !Array.isArray(obj)) {\n // Check for circular reference - only if this object is an ancestor in the current path\n if (pathSet.has(obj)) {\n return createNotImplemented(obj);\n }\n\n if (isSerializableLike(obj)) {\n // This is an LC object - serialize it properly (not escaped)\n return serializeLcObject(obj, pathSet);\n }\n\n // Add to path before processing children\n pathSet.add(obj);\n\n const record = obj as Record<string, unknown>;\n // Check if object needs escaping BEFORE recursing into values.\n // If it needs escaping, wrap it as-is - the contents are user data that\n // will be returned as-is during deserialization (no instantiation).\n // This prevents re-escaping of already-escaped nested content.\n if (needsEscaping(record)) {\n // Remove from path before returning (to allow shared references)\n pathSet.delete(obj);\n return escapeObject(record);\n }\n // Safe object (no 'lc' key) - recurse into values\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = serializeValue(value, pathSet);\n }\n // Remove from path after processing (to allow shared references in other branches)\n pathSet.delete(obj);\n return result;\n }\n\n if (Array.isArray(obj)) {\n // Arrays don't need circular reference tracking since they're handled by object tracking\n return obj.map((item) => serializeValue(item, pathSet));\n }\n\n if (\n typeof obj === \"string\" ||\n typeof obj === \"number\" ||\n typeof obj === \"boolean\" ||\n obj === null\n ) {\n return obj;\n }\n\n // Non-JSON-serializable object (Date, custom objects, etc.)\n return createNotImplemented(obj);\n}\n\n/**\n * Serialize a `Serializable` object with escaping of user data in kwargs.\n *\n * @param obj - The `Serializable` object to serialize.\n * @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references.\n * The Serializable object is kept in the path set to detect if it appears in its own kwargs.\n * @returns The serialized object with user data in kwargs escaped as needed.\n *\n * @remarks\n * Kwargs values are processed with `serializeValue` to escape user data (like\n * metadata) that contains `'lc'` keys. Secret fields (from `lc_secrets`) are\n * skipped because `toJSON()` replaces their values with secret markers.\n */\nexport function serializeLcObject(\n obj: SerializableLike,\n pathSet: WeakSet<object> = new WeakSet()\n): {\n lc: number;\n type: string;\n id: string[];\n kwargs?: Record<string, unknown>;\n} {\n // Add object to path set to detect if it appears in its own kwargs (circular reference)\n // Note: We intentionally don't remove this after processing because a Serializable\n // appearing in its own kwargs is always a circular reference that should be detected.\n pathSet.add(obj);\n\n // Secret fields are handled by toJSON() - it replaces values with secret markers\n const secretFields = new Set(Object.keys(obj.lc_secrets ?? {}));\n\n const serialized = { ...obj.toJSON() };\n\n // Process kwargs to escape user data that could be confused with LC objects\n // Skip secret fields - toJSON() already converted them to secret markers\n if (serialized.type === \"constructor\" && serialized.kwargs) {\n const newKwargs: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(serialized.kwargs)) {\n if (secretFields.has(key)) {\n newKwargs[key] = value;\n } else {\n newKwargs[key] = serializeValue(value, pathSet);\n }\n }\n serialized.kwargs = newKwargs;\n }\n\n return serialized;\n}\n\n/**\n * Escape a value if it needs escaping (contains `lc` key).\n *\n * This is a simpler version of `serializeValue` that doesn't handle Serializable\n * objects - it's meant to be called on kwargs values that have already been\n * processed by `toJSON()`.\n *\n * @param value - The value to potentially escape.\n * @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references.\n * Objects are removed after processing to allow shared references (same object in\n * multiple places) while still detecting true circular references (ancestor in descendant).\n * @returns The value with any `lc`-containing objects wrapped in escape markers.\n */\nexport function escapeIfNeeded(\n value: unknown,\n pathSet: WeakSet<object> = new WeakSet()\n): unknown {\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n // Check for circular reference - only if this object is an ancestor in the current path\n if (pathSet.has(value)) {\n // Replace circular reference with a not_implemented marker\n return createNotImplemented(value);\n }\n\n // Preserve Serializable objects - they have their own toJSON() that will be\n // called by JSON.stringify. We don't want to convert them to plain objects.\n if (isSerializableLike(value)) {\n return value;\n }\n\n // Add to path before processing children\n pathSet.add(value);\n\n const record = value as Record<string, unknown>;\n // Check if object needs escaping BEFORE recursing into values.\n // If it needs escaping, wrap it as-is - the contents are user data that\n // will be returned as-is during deserialization (no instantiation).\n if (needsEscaping(record)) {\n // Remove from path before returning (to allow shared references)\n pathSet.delete(value);\n return escapeObject(record);\n }\n // Safe object (no 'lc' key) - recurse into values\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(record)) {\n result[key] = escapeIfNeeded(val, pathSet);\n }\n // Remove from path after processing (to allow shared references in other branches)\n pathSet.delete(value);\n return result;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => escapeIfNeeded(item, pathSet));\n }\n\n return value;\n}\n\n/**\n * Unescape a value, processing escape markers in object values and arrays.\n *\n * When an escaped object is encountered (`{\"__lc_escaped__\": ...}`), it's\n * unwrapped and the contents are returned AS-IS (no further processing).\n * The contents represent user data that should not be modified.\n *\n * For regular objects and arrays, we recurse to find any nested escape markers.\n *\n * @param obj - The value to unescape.\n * @returns The unescaped value.\n */\nexport function unescapeValue(obj: unknown): unknown {\n if (obj !== null && typeof obj === \"object\" && !Array.isArray(obj)) {\n const record = obj as Record<string, unknown>;\n if (isEscapedObject(record)) {\n // Unwrap and return the user data as-is (no further unescaping).\n // The contents are user data that may contain more escape keys,\n // but those are part of the user's actual data.\n return record[LC_ESCAPED_KEY];\n }\n\n // Regular object - recurse into values to find nested escape markers\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = unescapeValue(value);\n }\n return result;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => unescapeValue(item));\n }\n\n return obj;\n}\n"],"mappings":";;;;;;;AAMA,MAAa,iBAAiB;;;;;;;;AAS9B,SAAgB,cAAc,KAAuC;CACnE,OACE,QAAQ,OAAQ,OAAO,KAAK,GAAG,CAAC,CAAC,WAAW,KAAA,oBAAuB;AAEvE;;;;;;;;;AAUA,SAAgB,aACd,KACyB;CACzB,OAAO,GAAG,iBAAiB,IAAI;AACjC;;;;;;;;;AAUA,SAAgB,gBAAgB,KAAuC;CACrE,OAAO,OAAO,KAAK,GAAG,CAAC,CAAC,WAAW,KAAA,oBAAuB;AAC5D;;;;AAoBA,SAAS,mBAAmB,KAAuC;CACjE,OACE,QAAQ,QACR,OAAO,QAAQ,YACf,qBAAqB,OACrB,OAAQ,IAAyB,WAAW;AAEhD;;;;AAKA,SAAS,qBAAqB,KAI5B;CACA,IAAI;CACJ,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UACjC,IAAI,WAAW,OAAO,MAAM,QAAQ,IAAI,KAAK,GAC3C,KAAK,IAAI;MAET,KAAK,CAAC,IAAI,aAAa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user objects during serialization.\n *\n * When a plain object contains 'lc' key (which could be confused with LC objects),\n * we wrap it as `{\"__lc_escaped__\": {...original...}}`.\n */\nexport const LC_ESCAPED_KEY = \"__lc_escaped__\";\n\n/**\n * Check if an object needs escaping to prevent confusion with LC objects.\n *\n * An object needs escaping if:\n * 1. It has an `'lc'` key (could be confused with LC serialization format)\n * 2. It has only the escape key (would be mistaken for an escaped object)\n */\nexport function needsEscaping(obj: Record<string, unknown>): boolean {\n return (\n \"lc\" in obj || (Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj)\n );\n}\n\n/**\n * Wrap an object in the escape marker.\n *\n * @example\n * ```typescript\n * {\"key\": \"value\"} // becomes {\"__lc_escaped__\": {\"key\": \"value\"}}\n * ```\n */\nexport function escapeObject(\n obj: Record<string, unknown>\n): Record<string, unknown> {\n return { [LC_ESCAPED_KEY]: obj };\n}\n\n/**\n * Check if an object is an escaped user object.\n *\n * @example\n * ```typescript\n * {\"__lc_escaped__\": {...}} // is an escaped object\n * ```\n */\nexport function isEscapedObject(obj: Record<string, unknown>): boolean {\n return Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj;\n}\n\n/**\n * Interface for objects that can be serialized.\n * This is a duck-typed interface to avoid circular imports.\n */\ninterface SerializableLike {\n lc_serializable: boolean;\n lc_secrets?: Record<string, string>;\n toJSON(): {\n lc: number;\n type: string;\n id: string[];\n kwargs?: Record<string, unknown>;\n };\n}\n\n/**\n * Check if an object looks like a Serializable instance (duck typing).\n */\nfunction isSerializableLike(obj: unknown): obj is SerializableLike {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"lc_serializable\" in obj &&\n typeof (obj as SerializableLike).toJSON === \"function\"\n );\n}\n\n/**\n * Create a \"not_implemented\" serialization result for objects that cannot be serialized.\n */\nfunction createNotImplemented(obj: unknown): {\n lc: 1;\n type: \"not_implemented\";\n id: string[];\n} {\n let id: string[];\n if (obj !== null && typeof obj === \"object\") {\n if (\"lc_id\" in obj && Array.isArray(obj.lc_id)) {\n id = obj.lc_id as string[];\n } else {\n id = [obj.constructor?.name ?? \"Object\"];\n }\n } else {\n id = [typeof obj];\n }\n return {\n lc: 1,\n type: \"not_implemented\",\n id,\n };\n}\n\n/**\n * Serialize a value with escaping of user objects.\n *\n * Called recursively on kwarg values to escape any plain objects that could be\n * confused with LC objects.\n *\n * @param obj - The value to serialize.\n * @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references.\n * Objects are removed after processing to allow shared references (same object in\n * multiple places) while still detecting true circular references (ancestor in descendant).\n * @returns The serialized value with user objects escaped as needed.\n */\nexport function serializeValue(\n obj: unknown,\n pathSet: WeakSet<object> = new WeakSet()\n): unknown {\n if (obj !== null && typeof obj === \"object\" && !Array.isArray(obj)) {\n // Check for circular reference - only if this object is an ancestor in the current path\n if (pathSet.has(obj)) {\n return createNotImplemented(obj);\n }\n\n if (isSerializableLike(obj)) {\n // This is an LC object - serialize it properly (not escaped)\n return serializeLcObject(obj, pathSet);\n }\n\n // Add to path before processing children\n pathSet.add(obj);\n\n const record = obj as Record<string, unknown>;\n // Check if object needs escaping BEFORE recursing into values.\n // If it needs escaping, wrap it as-is - the contents are user data that\n // will be returned as-is during deserialization (no instantiation).\n // This prevents re-escaping of already-escaped nested content.\n if (needsEscaping(record)) {\n // Remove from path before returning (to allow shared references)\n pathSet.delete(obj);\n return escapeObject(record);\n }\n // Safe object (no 'lc' key) - recurse into values\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = serializeValue(value, pathSet);\n }\n // Remove from path after processing (to allow shared references in other branches)\n pathSet.delete(obj);\n return result;\n }\n\n if (Array.isArray(obj)) {\n // Arrays don't need circular reference tracking since they're handled by object tracking\n return obj.map((item) => serializeValue(item, pathSet));\n }\n\n if (\n typeof obj === \"string\" ||\n typeof obj === \"number\" ||\n typeof obj === \"boolean\" ||\n obj === null\n ) {\n return obj;\n }\n\n // Non-JSON-serializable object (Date, custom objects, etc.)\n return createNotImplemented(obj);\n}\n\n/**\n * Serialize a `Serializable` object with escaping of user data in kwargs.\n *\n * @param obj - The `Serializable` object to serialize.\n * @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references.\n * The Serializable object is kept in the path set to detect if it appears in its own kwargs.\n * @returns The serialized object with user data in kwargs escaped as needed.\n *\n * @remarks\n * Kwargs values are processed with `serializeValue` to escape user data (like\n * metadata) that contains `'lc'` keys. Secret fields (from `lc_secrets`) are\n * skipped because `toJSON()` replaces their values with secret markers.\n */\nexport function serializeLcObject(\n obj: SerializableLike,\n pathSet: WeakSet<object> = new WeakSet()\n): {\n lc: number;\n type: string;\n id: string[];\n kwargs?: Record<string, unknown>;\n} {\n // Add object to path set to detect if it appears in its own kwargs (circular reference)\n // Note: We intentionally don't remove this after processing because a Serializable\n // appearing in its own kwargs is always a circular reference that should be detected.\n pathSet.add(obj);\n\n // Secret fields are handled by toJSON() - it replaces values with secret markers\n const secretFields = new Set(Object.keys(obj.lc_secrets ?? {}));\n\n const serialized = { ...obj.toJSON() };\n\n // Process kwargs to escape user data that could be confused with LC objects\n // Skip secret fields - toJSON() already converted them to secret markers\n if (serialized.type === \"constructor\" && serialized.kwargs) {\n const newKwargs: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(serialized.kwargs)) {\n if (secretFields.has(key)) {\n newKwargs[key] = value;\n } else {\n newKwargs[key] = serializeValue(value, pathSet);\n }\n }\n serialized.kwargs = newKwargs;\n }\n\n return serialized;\n}\n\n/**\n * Escape a value if it needs escaping (contains `lc` key).\n *\n * This is a simpler version of `serializeValue` that doesn't handle Serializable\n * objects - it's meant to be called on kwargs values that have already been\n * processed by `toJSON()`.\n *\n * @param value - The value to potentially escape.\n * @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references.\n * Objects are removed after processing to allow shared references (same object in\n * multiple places) while still detecting true circular references (ancestor in descendant).\n * @returns The value with any `lc`-containing objects wrapped in escape markers.\n */\nexport function escapeIfNeeded(\n value: unknown,\n pathSet: WeakSet<object> = new WeakSet()\n): unknown {\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n // Check for circular reference - only if this object is an ancestor in the current path\n if (pathSet.has(value)) {\n // Replace circular reference with a not_implemented marker\n return createNotImplemented(value);\n }\n\n // Preserve Serializable objects - they have their own toJSON() that will be\n // called by JSON.stringify. We don't want to convert them to plain objects.\n if (isSerializableLike(value)) {\n return value;\n }\n\n // Add to path before processing children\n pathSet.add(value);\n\n const record = value as Record<string, unknown>;\n // Check if object needs escaping BEFORE recursing into values.\n // If it needs escaping, wrap it as-is - the contents are user data that\n // will be returned as-is during deserialization (no instantiation).\n if (needsEscaping(record)) {\n // Remove from path before returning (to allow shared references)\n pathSet.delete(value);\n return escapeObject(record);\n }\n // Safe object (no 'lc' key) - recurse into values\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(record)) {\n result[key] = escapeIfNeeded(val, pathSet);\n }\n // Remove from path after processing (to allow shared references in other branches)\n pathSet.delete(value);\n return result;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => escapeIfNeeded(item, pathSet));\n }\n\n return value;\n}\n\n/**\n * Unescape a value, processing escape markers in object values and arrays.\n *\n * When an escaped object is encountered (`{\"__lc_escaped__\": ...}`), it's\n * unwrapped and the contents are returned AS-IS (no further processing).\n * The contents represent user data that should not be modified.\n *\n * For regular objects and arrays, we recurse to find any nested escape markers.\n *\n * @param obj - The value to unescape.\n * @returns The unescaped value.\n */\nexport function unescapeValue(obj: unknown): unknown {\n if (obj !== null && typeof obj === \"object\" && !Array.isArray(obj)) {\n const record = obj as Record<string, unknown>;\n if (isEscapedObject(record)) {\n // Unwrap and return the user data as-is (no further unescaping).\n // The contents are user data that may contain more escape keys,\n // but those are part of the user's actual data.\n return record[LC_ESCAPED_KEY];\n }\n\n // Regular object - recurse into values to find nested escape markers\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = unescapeValue(value);\n }\n return result;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => unescapeValue(item));\n }\n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,KAAK,OAAO;EAG3C,QAAQ,OAAO,KAAK;EACpB,OAAO;CACT;CAEA,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,KAAK,SAAS,eAAe,MAAM,OAAO,CAAC;CAG1D,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,cAAc,KAAuB;CACnD,IAAI,QAAQ,QAAQ,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ,GAAG,GAAG;EAClE,MAAM,SAAS;EACf,IAAI,gBAAgB,MAAM,GAIxB,OAAO,OAAO;EAIhB,MAAM,SAAkC,CAAC;EACzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,OAAO,OAAO,cAAc,KAAK;EAEnC,OAAO;CACT;CAEA,IAAI,MAAM,QAAQ,GAAG,GACnB,OAAO,IAAI,KAAK,SAAS,cAAc,IAAI,CAAC;CAG9C,OAAO;AACT"}
@@ -49,9 +49,10 @@ function isSerializableLike(obj) {
49
49
  */
50
50
  function createNotImplemented(obj) {
51
51
  let id;
52
- if (obj !== null && typeof obj === "object") if ("lc_id" in obj && Array.isArray(obj.lc_id)) id = obj.lc_id;
53
- else id = [obj.constructor?.name ?? "Object"];
54
- else id = [typeof obj];
52
+ if (obj !== null && typeof obj === "object") {
53
+ if ("lc_id" in obj && Array.isArray(obj.lc_id)) id = obj.lc_id;
54
+ else id = [obj.constructor?.name ?? "Object"];
55
+ } else id = [typeof obj];
55
56
  return {
56
57
  lc: 1,
57
58
  type: "not_implemented",
@@ -1 +1 @@
1
- {"version":3,"file":"validation.js","names":[],"sources":["../../src/load/validation.ts"],"sourcesContent":["/**\n * Sentinel key used to mark escaped user objects during serialization.\n *\n * When a plain object contains 'lc' key (which could be confused with LC objects),\n * we wrap it as `{\"__lc_escaped__\": {...original...}}`.\n */\nexport const LC_ESCAPED_KEY = \"__lc_escaped__\";\n\n/**\n * Check if an object needs escaping to prevent confusion with LC objects.\n *\n * An object needs escaping if:\n * 1. It has an `'lc'` key (could be confused with LC serialization format)\n * 2. It has only the escape key (would be mistaken for an escaped object)\n */\nexport function needsEscaping(obj: Record<string, unknown>): boolean {\n return (\n \"lc\" in obj || (Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj)\n );\n}\n\n/**\n * Wrap an object in the escape marker.\n *\n * @example\n * ```typescript\n * {\"key\": \"value\"} // becomes {\"__lc_escaped__\": {\"key\": \"value\"}}\n * ```\n */\nexport function escapeObject(\n obj: Record<string, unknown>\n): Record<string, unknown> {\n return { [LC_ESCAPED_KEY]: obj };\n}\n\n/**\n * Check if an object is an escaped user object.\n *\n * @example\n * ```typescript\n * {\"__lc_escaped__\": {...}} // is an escaped object\n * ```\n */\nexport function isEscapedObject(obj: Record<string, unknown>): boolean {\n return Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj;\n}\n\n/**\n * Interface for objects that can be serialized.\n * This is a duck-typed interface to avoid circular imports.\n */\ninterface SerializableLike {\n lc_serializable: boolean;\n lc_secrets?: Record<string, string>;\n toJSON(): {\n lc: number;\n type: string;\n id: string[];\n kwargs?: Record<string, unknown>;\n };\n}\n\n/**\n * Check if an object looks like a Serializable instance (duck typing).\n */\nfunction isSerializableLike(obj: unknown): obj is SerializableLike {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"lc_serializable\" in obj &&\n typeof (obj as SerializableLike).toJSON === \"function\"\n );\n}\n\n/**\n * Create a \"not_implemented\" serialization result for objects that cannot be serialized.\n */\nfunction createNotImplemented(obj: unknown): {\n lc: 1;\n type: \"not_implemented\";\n id: string[];\n} {\n let id: string[];\n if (obj !== null && typeof obj === \"object\") {\n if (\"lc_id\" in obj && Array.isArray(obj.lc_id)) {\n id = obj.lc_id as string[];\n } else {\n id = [obj.constructor?.name ?? \"Object\"];\n }\n } else {\n id = [typeof obj];\n }\n return {\n lc: 1,\n type: \"not_implemented\",\n id,\n };\n}\n\n/**\n * Serialize a value with escaping of user objects.\n *\n * Called recursively on kwarg values to escape any plain objects that could be\n * confused with LC objects.\n *\n * @param obj - The value to serialize.\n * @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references.\n * Objects are removed after processing to allow shared references (same object in\n * multiple places) while still detecting true circular references (ancestor in descendant).\n * @returns The serialized value with user objects escaped as needed.\n */\nexport function serializeValue(\n obj: unknown,\n pathSet: WeakSet<object> = new WeakSet()\n): unknown {\n if (obj !== null && typeof obj === \"object\" && !Array.isArray(obj)) {\n // Check for circular reference - only if this object is an ancestor in the current path\n if (pathSet.has(obj)) {\n return createNotImplemented(obj);\n }\n\n if (isSerializableLike(obj)) {\n // This is an LC object - serialize it properly (not escaped)\n return serializeLcObject(obj, pathSet);\n }\n\n // Add to path before processing children\n pathSet.add(obj);\n\n const record = obj as Record<string, unknown>;\n // Check if object needs escaping BEFORE recursing into values.\n // If it needs escaping, wrap it as-is - the contents are user data that\n // will be returned as-is during deserialization (no instantiation).\n // This prevents re-escaping of already-escaped nested content.\n if (needsEscaping(record)) {\n // Remove from path before returning (to allow shared references)\n pathSet.delete(obj);\n return escapeObject(record);\n }\n // Safe object (no 'lc' key) - recurse into values\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = serializeValue(value, pathSet);\n }\n // Remove from path after processing (to allow shared references in other branches)\n pathSet.delete(obj);\n return result;\n }\n\n if (Array.isArray(obj)) {\n // Arrays don't need circular reference tracking since they're handled by object tracking\n return obj.map((item) => serializeValue(item, pathSet));\n }\n\n if (\n typeof obj === \"string\" ||\n typeof obj === \"number\" ||\n typeof obj === \"boolean\" ||\n obj === null\n ) {\n return obj;\n }\n\n // Non-JSON-serializable object (Date, custom objects, etc.)\n return createNotImplemented(obj);\n}\n\n/**\n * Serialize a `Serializable` object with escaping of user data in kwargs.\n *\n * @param obj - The `Serializable` object to serialize.\n * @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references.\n * The Serializable object is kept in the path set to detect if it appears in its own kwargs.\n * @returns The serialized object with user data in kwargs escaped as needed.\n *\n * @remarks\n * Kwargs values are processed with `serializeValue` to escape user data (like\n * metadata) that contains `'lc'` keys. Secret fields (from `lc_secrets`) are\n * skipped because `toJSON()` replaces their values with secret markers.\n */\nexport function serializeLcObject(\n obj: SerializableLike,\n pathSet: WeakSet<object> = new WeakSet()\n): {\n lc: number;\n type: string;\n id: string[];\n kwargs?: Record<string, unknown>;\n} {\n // Add object to path set to detect if it appears in its own kwargs (circular reference)\n // Note: We intentionally don't remove this after processing because a Serializable\n // appearing in its own kwargs is always a circular reference that should be detected.\n pathSet.add(obj);\n\n // Secret fields are handled by toJSON() - it replaces values with secret markers\n const secretFields = new Set(Object.keys(obj.lc_secrets ?? {}));\n\n const serialized = { ...obj.toJSON() };\n\n // Process kwargs to escape user data that could be confused with LC objects\n // Skip secret fields - toJSON() already converted them to secret markers\n if (serialized.type === \"constructor\" && serialized.kwargs) {\n const newKwargs: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(serialized.kwargs)) {\n if (secretFields.has(key)) {\n newKwargs[key] = value;\n } else {\n newKwargs[key] = serializeValue(value, pathSet);\n }\n }\n serialized.kwargs = newKwargs;\n }\n\n return serialized;\n}\n\n/**\n * Escape a value if it needs escaping (contains `lc` key).\n *\n * This is a simpler version of `serializeValue` that doesn't handle Serializable\n * objects - it's meant to be called on kwargs values that have already been\n * processed by `toJSON()`.\n *\n * @param value - The value to potentially escape.\n * @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references.\n * Objects are removed after processing to allow shared references (same object in\n * multiple places) while still detecting true circular references (ancestor in descendant).\n * @returns The value with any `lc`-containing objects wrapped in escape markers.\n */\nexport function escapeIfNeeded(\n value: unknown,\n pathSet: WeakSet<object> = new WeakSet()\n): unknown {\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n // Check for circular reference - only if this object is an ancestor in the current path\n if (pathSet.has(value)) {\n // Replace circular reference with a not_implemented marker\n return createNotImplemented(value);\n }\n\n // Preserve Serializable objects - they have their own toJSON() that will be\n // called by JSON.stringify. We don't want to convert them to plain objects.\n if (isSerializableLike(value)) {\n return value;\n }\n\n // Add to path before processing children\n pathSet.add(value);\n\n const record = value as Record<string, unknown>;\n // Check if object needs escaping BEFORE recursing into values.\n // If it needs escaping, wrap it as-is - the contents are user data that\n // will be returned as-is during deserialization (no instantiation).\n if (needsEscaping(record)) {\n // Remove from path before returning (to allow shared references)\n pathSet.delete(value);\n return escapeObject(record);\n }\n // Safe object (no 'lc' key) - recurse into values\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(record)) {\n result[key] = escapeIfNeeded(val, pathSet);\n }\n // Remove from path after processing (to allow shared references in other branches)\n pathSet.delete(value);\n return result;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => escapeIfNeeded(item, pathSet));\n }\n\n return value;\n}\n\n/**\n * Unescape a value, processing escape markers in object values and arrays.\n *\n * When an escaped object is encountered (`{\"__lc_escaped__\": ...}`), it's\n * unwrapped and the contents are returned AS-IS (no further processing).\n * The contents represent user data that should not be modified.\n *\n * For regular objects and arrays, we recurse to find any nested escape markers.\n *\n * @param obj - The value to unescape.\n * @returns The unescaped value.\n */\nexport function unescapeValue(obj: unknown): unknown {\n if (obj !== null && typeof obj === \"object\" && !Array.isArray(obj)) {\n const record = obj as Record<string, unknown>;\n if (isEscapedObject(record)) {\n // Unwrap and return the user data as-is (no further unescaping).\n // The contents are user data that may contain more escape keys,\n // but those are part of the user's actual data.\n return record[LC_ESCAPED_KEY];\n }\n\n // Regular object - recurse into values to find nested escape markers\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = unescapeValue(value);\n }\n return result;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => unescapeValue(item));\n }\n\n return obj;\n}\n"],"mappings":";;;;;;;AAMA,MAAa,iBAAiB;;;;;;;;AAS9B,SAAgB,cAAc,KAAuC;CACnE,OACE,QAAQ,OAAQ,OAAO,KAAK,GAAG,CAAC,CAAC,WAAW,KAAA,oBAAuB;AAEvE;;;;;;;;;AAUA,SAAgB,aACd,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AI,QAAQ,QAAQ,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ,GAAG,GAAG;EAClE,MAAM,SAAS;EACf,IAAI,gBAAgB,MAAM,GAIxB,OAAO,OAAO;EAIhB,MAAM,SAAkC,CAAC;EACzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,OAAO,OAAO,cAAc,KAAK;EAEnC,OAAO;CACT;CAEA,IAAI,MAAM,QAAQ,GAAG,GACnB,OAAO,IAAI,KAAK,SAAS,cAAc,IAAI,CAAC;CAG9C,OAAO;AACT"}
1
+ {"version":3,"file":"validation.js","names":[],"sources":["../../src/load/validation.ts"],"sourcesContent":["/**\n * Sentinel key used to mark escaped user objects during serialization.\n *\n * When a plain object contains 'lc' key (which could be confused with LC objects),\n * we wrap it as `{\"__lc_escaped__\": {...original...}}`.\n */\nexport const LC_ESCAPED_KEY = \"__lc_escaped__\";\n\n/**\n * Check if an object needs escaping to prevent confusion with LC objects.\n *\n * An object needs escaping if:\n * 1. It has an `'lc'` key (could be confused with LC serialization format)\n * 2. It has only the escape key (would be mistaken for an escaped object)\n */\nexport function needsEscaping(obj: Record<string, unknown>): boolean {\n return (\n \"lc\" in obj || (Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj)\n );\n}\n\n/**\n * Wrap an object in the escape marker.\n *\n * @example\n * ```typescript\n * {\"key\": \"value\"} // becomes {\"__lc_escaped__\": {\"key\": \"value\"}}\n * ```\n */\nexport function escapeObject(\n obj: Record<string, unknown>\n): Record<string, unknown> {\n return { [LC_ESCAPED_KEY]: obj };\n}\n\n/**\n * Check if an object is an escaped user object.\n *\n * @example\n * ```typescript\n * {\"__lc_escaped__\": {...}} // is an escaped object\n * ```\n */\nexport function isEscapedObject(obj: Record<string, unknown>): boolean {\n return Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj;\n}\n\n/**\n * Interface for objects that can be serialized.\n * This is a duck-typed interface to avoid circular imports.\n */\ninterface SerializableLike {\n lc_serializable: boolean;\n lc_secrets?: Record<string, string>;\n toJSON(): {\n lc: number;\n type: string;\n id: string[];\n kwargs?: Record<string, unknown>;\n };\n}\n\n/**\n * Check if an object looks like a Serializable instance (duck typing).\n */\nfunction isSerializableLike(obj: unknown): obj is SerializableLike {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"lc_serializable\" in obj &&\n typeof (obj as SerializableLike).toJSON === \"function\"\n );\n}\n\n/**\n * Create a \"not_implemented\" serialization result for objects that cannot be serialized.\n */\nfunction createNotImplemented(obj: unknown): {\n lc: 1;\n type: \"not_implemented\";\n id: string[];\n} {\n let id: string[];\n if (obj !== null && typeof obj === \"object\") {\n if (\"lc_id\" in obj && Array.isArray(obj.lc_id)) {\n id = obj.lc_id as string[];\n } else {\n id = [obj.constructor?.name ?? \"Object\"];\n }\n } else {\n id = [typeof obj];\n }\n return {\n lc: 1,\n type: \"not_implemented\",\n id,\n };\n}\n\n/**\n * Serialize a value with escaping of user objects.\n *\n * Called recursively on kwarg values to escape any plain objects that could be\n * confused with LC objects.\n *\n * @param obj - The value to serialize.\n * @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references.\n * Objects are removed after processing to allow shared references (same object in\n * multiple places) while still detecting true circular references (ancestor in descendant).\n * @returns The serialized value with user objects escaped as needed.\n */\nexport function serializeValue(\n obj: unknown,\n pathSet: WeakSet<object> = new WeakSet()\n): unknown {\n if (obj !== null && typeof obj === \"object\" && !Array.isArray(obj)) {\n // Check for circular reference - only if this object is an ancestor in the current path\n if (pathSet.has(obj)) {\n return createNotImplemented(obj);\n }\n\n if (isSerializableLike(obj)) {\n // This is an LC object - serialize it properly (not escaped)\n return serializeLcObject(obj, pathSet);\n }\n\n // Add to path before processing children\n pathSet.add(obj);\n\n const record = obj as Record<string, unknown>;\n // Check if object needs escaping BEFORE recursing into values.\n // If it needs escaping, wrap it as-is - the contents are user data that\n // will be returned as-is during deserialization (no instantiation).\n // This prevents re-escaping of already-escaped nested content.\n if (needsEscaping(record)) {\n // Remove from path before returning (to allow shared references)\n pathSet.delete(obj);\n return escapeObject(record);\n }\n // Safe object (no 'lc' key) - recurse into values\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = serializeValue(value, pathSet);\n }\n // Remove from path after processing (to allow shared references in other branches)\n pathSet.delete(obj);\n return result;\n }\n\n if (Array.isArray(obj)) {\n // Arrays don't need circular reference tracking since they're handled by object tracking\n return obj.map((item) => serializeValue(item, pathSet));\n }\n\n if (\n typeof obj === \"string\" ||\n typeof obj === \"number\" ||\n typeof obj === \"boolean\" ||\n obj === null\n ) {\n return obj;\n }\n\n // Non-JSON-serializable object (Date, custom objects, etc.)\n return createNotImplemented(obj);\n}\n\n/**\n * Serialize a `Serializable` object with escaping of user data in kwargs.\n *\n * @param obj - The `Serializable` object to serialize.\n * @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references.\n * The Serializable object is kept in the path set to detect if it appears in its own kwargs.\n * @returns The serialized object with user data in kwargs escaped as needed.\n *\n * @remarks\n * Kwargs values are processed with `serializeValue` to escape user data (like\n * metadata) that contains `'lc'` keys. Secret fields (from `lc_secrets`) are\n * skipped because `toJSON()` replaces their values with secret markers.\n */\nexport function serializeLcObject(\n obj: SerializableLike,\n pathSet: WeakSet<object> = new WeakSet()\n): {\n lc: number;\n type: string;\n id: string[];\n kwargs?: Record<string, unknown>;\n} {\n // Add object to path set to detect if it appears in its own kwargs (circular reference)\n // Note: We intentionally don't remove this after processing because a Serializable\n // appearing in its own kwargs is always a circular reference that should be detected.\n pathSet.add(obj);\n\n // Secret fields are handled by toJSON() - it replaces values with secret markers\n const secretFields = new Set(Object.keys(obj.lc_secrets ?? {}));\n\n const serialized = { ...obj.toJSON() };\n\n // Process kwargs to escape user data that could be confused with LC objects\n // Skip secret fields - toJSON() already converted them to secret markers\n if (serialized.type === \"constructor\" && serialized.kwargs) {\n const newKwargs: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(serialized.kwargs)) {\n if (secretFields.has(key)) {\n newKwargs[key] = value;\n } else {\n newKwargs[key] = serializeValue(value, pathSet);\n }\n }\n serialized.kwargs = newKwargs;\n }\n\n return serialized;\n}\n\n/**\n * Escape a value if it needs escaping (contains `lc` key).\n *\n * This is a simpler version of `serializeValue` that doesn't handle Serializable\n * objects - it's meant to be called on kwargs values that have already been\n * processed by `toJSON()`.\n *\n * @param value - The value to potentially escape.\n * @param pathSet - WeakSet to track ancestor objects in the current path to detect circular references.\n * Objects are removed after processing to allow shared references (same object in\n * multiple places) while still detecting true circular references (ancestor in descendant).\n * @returns The value with any `lc`-containing objects wrapped in escape markers.\n */\nexport function escapeIfNeeded(\n value: unknown,\n pathSet: WeakSet<object> = new WeakSet()\n): unknown {\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n // Check for circular reference - only if this object is an ancestor in the current path\n if (pathSet.has(value)) {\n // Replace circular reference with a not_implemented marker\n return createNotImplemented(value);\n }\n\n // Preserve Serializable objects - they have their own toJSON() that will be\n // called by JSON.stringify. We don't want to convert them to plain objects.\n if (isSerializableLike(value)) {\n return value;\n }\n\n // Add to path before processing children\n pathSet.add(value);\n\n const record = value as Record<string, unknown>;\n // Check if object needs escaping BEFORE recursing into values.\n // If it needs escaping, wrap it as-is - the contents are user data that\n // will be returned as-is during deserialization (no instantiation).\n if (needsEscaping(record)) {\n // Remove from path before returning (to allow shared references)\n pathSet.delete(value);\n return escapeObject(record);\n }\n // Safe object (no 'lc' key) - recurse into values\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(record)) {\n result[key] = escapeIfNeeded(val, pathSet);\n }\n // Remove from path after processing (to allow shared references in other branches)\n pathSet.delete(value);\n return result;\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => escapeIfNeeded(item, pathSet));\n }\n\n return value;\n}\n\n/**\n * Unescape a value, processing escape markers in object values and arrays.\n *\n * When an escaped object is encountered (`{\"__lc_escaped__\": ...}`), it's\n * unwrapped and the contents are returned AS-IS (no further processing).\n * The contents represent user data that should not be modified.\n *\n * For regular objects and arrays, we recurse to find any nested escape markers.\n *\n * @param obj - The value to unescape.\n * @returns The unescaped value.\n */\nexport function unescapeValue(obj: unknown): unknown {\n if (obj !== null && typeof obj === \"object\" && !Array.isArray(obj)) {\n const record = obj as Record<string, unknown>;\n if (isEscapedObject(record)) {\n // Unwrap and return the user data as-is (no further unescaping).\n // The contents are user data that may contain more escape keys,\n // but those are part of the user's actual data.\n return record[LC_ESCAPED_KEY];\n }\n\n // Regular object - recurse into values to find nested escape markers\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = unescapeValue(value);\n }\n return result;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => unescapeValue(item));\n }\n\n return obj;\n}\n"],"mappings":";;;;;;;AAMA,MAAa,iBAAiB;;;;;;;;AAS9B,SAAgB,cAAc,KAAuC;CACnE,OACE,QAAQ,OAAQ,OAAO,KAAK,GAAG,CAAC,CAAC,WAAW,KAAA,oBAAuB;AAEvE;;;;;;;;;AAUA,SAAgB,aACd,KACyB;CACzB,OAAO,GAAG,iBAAiB,IAAI;AACjC;;;;;;;;;AAUA,SAAgB,gBAAgB,KAAuC;CACrE,OAAO,OAAO,KAAK,GAAG,CAAC,CAAC,WAAW,KAAA,oBAAuB;AAC5D;;;;AAoBA,SAAS,mBAAmB,KAAuC;CACjE,OACE,QAAQ,QACR,OAAO,QAAQ,YACf,qBAAqB,OACrB,OAAQ,IAAyB,WAAW;AAEhD;;;;AAKA,SAAS,qBAAqB,KAI5B;CACA,IAAI;CACJ,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;EAC3C,IAAI,WAAW,OAAO,MAAM,QAAQ,IAAI,KAAK,GAC3C,KAAK,IAAI;OAET,KAAK,CAAC,IAAI,aAAa,QAAQ,QAAQ;CAE3C,OACE,KAAK,CAAC,OAAO,GAAG;CAElB,OAAO;EACL,IAAI;EACJ,MAAM;EACN;CACF;AACF;;;;;;;;;;;;;;AAoIA,SAAgB,eACd,OACA,0BAA2B,IAAI,QAAQ,GAC9B;CACT,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,GAAG;EAExE,IAAI,QAAQ,IAAI,KAAK,GAEnB,OAAO,qBAAqB,KAAK;EAKnC,IAAI,mBAAmB,KAAK,GAC1B,OAAO;EAIT,QAAQ,IAAI,KAAK;EAEjB,MAAM,SAAS;EAIf,IAAI,cAAc,MAAM,GAAG;GAEzB,QAAQ,OAAO,KAAK;GACpB,OAAO,aAAa,MAAM;EAC5B;EAEA,MAAM,SAAkC,CAAC;EACzC,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,MAAM,GAC5C,OAAO,OAAO,eAAe,KAAK,OAAO;EAG3C,QAAQ,OAAO,KAAK;EACpB,OAAO;CACT;CAEA,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,KAAK,SAAS,eAAe,MAAM,OAAO,CAAC;CAG1D,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,cAAc,KAAuB;CACnD,IAAI,QAAQ,QAAQ,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ,GAAG,GAAG;EAClE,MAAM,SAAS;EACf,IAAI,gBAAgB,MAAM,GAIxB,OAAO,OAAO;EAIhB,MAAM,SAAkC,CAAC;EACzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,OAAO,OAAO,cAAc,KAAK;EAEnC,OAAO;CACT;CAEA,IAAI,MAAM,QAAQ,GAAG,GACnB,OAAO,IAAI,KAAK,SAAS,cAAc,IAAI,CAAC;CAG9C,OAAO;AACT"}
@@ -142,13 +142,7 @@ var BaseMessage = class extends require_load_serializable.Serializable {
142
142
  }
143
143
  /** Get text content of the message. */
144
144
  get text() {
145
- if (typeof this.content === "string") return this.content;
146
- if (!Array.isArray(this.content)) return "";
147
- return this.content.map((c) => {
148
- if (typeof c === "string") return c;
149
- if (c.type === "text") return c.text;
150
- return "";
151
- }).join("");
145
+ return this.contentBlocks.filter((block) => block.type === "text").reduce((acc, block) => acc + (block.text ?? ""), "");
152
146
  }
153
147
  get contentBlocks() {
154
148
  const blocks = typeof this.content === "string" ? [{
@@ -224,17 +218,18 @@ function _mergeDicts(left, right, options) {
224
218
  for (const [key, value] of Object.entries(right)) if (merged[key] == null) merged[key] = value;
225
219
  else if (value == null) continue;
226
220
  else if (typeof merged[key] !== typeof value || Array.isArray(merged[key]) !== Array.isArray(value)) throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`);
227
- else if (typeof merged[key] === "string") if (key === "type") continue;
228
- else if ([
229
- "id",
230
- "name",
231
- "output_version",
232
- "model_provider"
233
- ].includes(key)) {
234
- if (value) merged[key] = value;
235
- } else if (ignoreKeys.includes(key)) continue;
236
- else merged[key] += value;
237
- else if (typeof merged[key] === "number") {
221
+ else if (typeof merged[key] === "string") {
222
+ if (key === "type") continue;
223
+ else if ([
224
+ "id",
225
+ "name",
226
+ "output_version",
227
+ "model_provider"
228
+ ].includes(key)) {
229
+ if (value) merged[key] = value;
230
+ } else if (ignoreKeys.includes(key)) continue;
231
+ else merged[key] += value;
232
+ } else if (typeof merged[key] === "number") {
238
233
  if (ignoreKeys.includes(key)) continue;
239
234
  merged[key] = merged[key] + value;
240
235
  } else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) merged[key] = _mergeDicts(merged[key], value, options);
@@ -1 +1 @@
1
- {"version":3,"file":"base.cjs","names":["isDataContentBlock","Serializable","convertToV1FromDataContent","convertToV1FromChatCompletionsInput","convertToV1FromAnthropicInput","isMessage","convertToFormattedString"],"sources":["../../src/messages/base.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { isDataContentBlock } from \"./content/data.js\";\nimport { convertToV1FromAnthropicInput } from \"./block_translators/anthropic.js\";\nimport { convertToV1FromDataContent } from \"./block_translators/data.js\";\nimport { convertToV1FromChatCompletionsInput } from \"./block_translators/openai.js\";\nimport {\n $InferMessageContent,\n $InferResponseMetadata,\n MessageStructure,\n MessageType,\n isMessage,\n Message,\n} from \"./message.js\";\nimport {\n convertToFormattedString,\n type MessageStringFormat,\n} from \"./format.js\";\n\n/** @internal */\nconst MESSAGE_SYMBOL: symbol = Symbol.for(\"langchain.message\");\n\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n response_metadata?: Record<string, any>;\n id?: string;\n}\n\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\n\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\n\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\n\nexport type MessageContent = string | Array<ContentBlock>;\n\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n}\n\nexport type BaseMessageFields<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n> = Pick<Message, \"id\" | \"name\"> & {\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\n\n/**\n * Normalize non-string `firstContent` to a block array for merge/spread.\n * Some serializers (e.g. Anthropic-style) yield a single block object instead of a one-element array;\n * spreading that object as an array throws (\"is not iterable\").\n */\nfunction contentBlocksFromNonStringFirst(\n firstContent: MessageContent\n): ContentBlock[] {\n if (Array.isArray(firstContent)) {\n return firstContent;\n }\n if (typeof firstContent === \"string\") {\n return firstContent === \"\" ? [] : [{ type: \"text\", text: firstContent }];\n }\n if (firstContent == null) {\n return [];\n }\n return [firstContent as ContentBlock];\n}\n\nexport function mergeContent(\n firstContent: MessageContent,\n secondContent: MessageContent\n): MessageContent {\n // If first content is a string\n if (typeof firstContent === \"string\") {\n if (firstContent === \"\") {\n return secondContent;\n }\n if (typeof secondContent === \"string\") {\n return firstContent + secondContent;\n } else if (Array.isArray(secondContent) && secondContent.length === 0) {\n return firstContent;\n } else if (\n Array.isArray(secondContent) &&\n secondContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n {\n type: \"text\",\n source_type: \"text\",\n text: firstContent,\n },\n ...secondContent,\n ];\n } else {\n return [{ type: \"text\", text: firstContent }, ...secondContent];\n }\n // If both are arrays\n } else if (Array.isArray(secondContent)) {\n const left = contentBlocksFromNonStringFirst(firstContent);\n return _mergeLists(left, secondContent) ?? [...left, ...secondContent];\n } else {\n if (secondContent === \"\") {\n return firstContent;\n } else if (\n Array.isArray(firstContent) &&\n firstContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n ...firstContent,\n {\n type: \"file\",\n source_type: \"text\",\n text: secondContent,\n },\n ];\n } else {\n const left = contentBlocksFromNonStringFirst(firstContent);\n return [...left, { type: \"text\", text: secondContent }];\n }\n }\n}\n\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport function _mergeStatus(\n left?: \"success\" | \"error\",\n right?: \"success\" | \"error\"\n): \"success\" | \"error\" | undefined {\n if (left === \"error\" || right === \"error\") {\n return \"error\";\n }\n return \"success\";\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringifyWithDepthLimit(obj: any, depthLimit: number): string {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n function helper(obj: any, currentDepth: number): any {\n if (typeof obj !== \"object\" || obj === null || obj === undefined) {\n return obj;\n }\n if (currentDepth >= depthLimit) {\n if (Array.isArray(obj)) {\n return \"[Array]\";\n }\n return \"[Object]\";\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => helper(item, currentDepth + 1));\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = helper(obj[key], currentDepth + 1);\n }\n return result;\n }\n\n return JSON.stringify(helper(obj, 0), null, 2);\n}\n\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport abstract class BaseMessage<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n>\n extends Serializable\n implements Message<TStructure, TRole>\n{\n lc_namespace = [\"langchain_core\", \"messages\"];\n\n lc_serializable = true;\n\n get lc_aliases(): Record<string, string> {\n // exclude snake case conversion to pascal case\n return {\n additional_kwargs: \"additional_kwargs\",\n response_metadata: \"response_metadata\",\n };\n }\n\n readonly [MESSAGE_SYMBOL] = true as const;\n\n abstract readonly type: TRole;\n\n id?: string;\n\n /** @inheritdoc */\n name?: string;\n\n content: $InferMessageContent<TStructure, TRole>;\n\n additional_kwargs: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]\n >;\n\n response_metadata: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"response_metadata\"]\n >;\n\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType {\n return this.type;\n }\n\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType {\n return this._getType();\n }\n\n constructor(\n arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>\n ) {\n const fields: BaseMessageFields<TStructure, TRole> =\n typeof arg === \"string\" || Array.isArray(arg)\n ? ({ content: arg } as BaseMessageFields<TStructure, TRole>)\n : arg;\n if (!fields.additional_kwargs) {\n fields.additional_kwargs = {};\n }\n if (!fields.response_metadata) {\n fields.response_metadata = {};\n }\n super(fields);\n this.name = fields.name;\n if (fields.content === undefined && fields.contentBlocks !== undefined) {\n this.content = fields.contentBlocks as $InferMessageContent<\n TStructure,\n TRole\n >;\n this.response_metadata = {\n output_version: \"v1\",\n ...fields.response_metadata,\n };\n } else if (fields.content !== undefined) {\n this.content = fields.content ?? [];\n this.response_metadata = fields.response_metadata;\n } else {\n this.content = [] as $InferMessageContent<TStructure, TRole>;\n this.response_metadata = fields.response_metadata;\n }\n this.additional_kwargs = fields.additional_kwargs;\n this.id = fields.id;\n }\n\n /** Get text content of the message. */\n get text(): string {\n if (typeof this.content === \"string\") {\n return this.content;\n }\n if (!Array.isArray(this.content)) return \"\";\n return this.content\n .map((c) => {\n if (typeof c === \"string\") return c;\n if (c.type === \"text\") return c.text;\n return \"\";\n })\n .join(\"\");\n }\n\n get contentBlocks(): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock> =\n typeof this.content === \"string\"\n ? [{ type: \"text\", text: this.content }]\n : this.content;\n const parsingSteps = [\n convertToV1FromDataContent,\n convertToV1FromChatCompletionsInput,\n convertToV1FromAnthropicInput,\n ];\n const parsedBlocks = parsingSteps.reduce(\n (blocks, step) => step(blocks),\n blocks\n );\n return parsedBlocks as Array<ContentBlock.Standard>;\n }\n\n toDict(): StoredMessage {\n return {\n type: this.getType(),\n data: (this.toJSON() as SerializedConstructor)\n .kwargs as StoredMessageData,\n };\n }\n\n static lc_name() {\n return \"BaseMessage\";\n }\n\n // Can't be protected for silly reasons\n get _printableFields(): Record<string, unknown> {\n return {\n id: this.id,\n content: this.content,\n name: this.name,\n additional_kwargs: this.additional_kwargs,\n response_metadata: this.response_metadata,\n };\n }\n\n static isInstance(obj: unknown): obj is BaseMessage {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n MESSAGE_SYMBOL in obj &&\n (obj as Record<symbol, unknown>)[MESSAGE_SYMBOL] === true &&\n isMessage(obj)\n );\n }\n\n static [Symbol.hasInstance](obj: unknown) {\n return this.isInstance(obj);\n }\n\n // this private method is used to update the ID for the runtime\n // value as well as in lc_kwargs for serialisation\n _updateId(value: string | undefined) {\n this.id = value;\n\n // lc_attributes wouldn't work here, because jest compares the\n // whole object\n this.lc_kwargs.id = value;\n }\n\n get [Symbol.toStringTag]() {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.constructor as any).lc_name();\n }\n\n // Override the default behavior of console.log\n [Symbol.for(\"nodejs.util.inspect.custom\")](depth: number | null) {\n if (depth === null) {\n return this;\n }\n const printable = stringifyWithDepthLimit(\n this._printableFields,\n Math.max(4, depth)\n );\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return `${(this.constructor as any).lc_name()} ${printable}`;\n }\n\n toFormattedString(format: MessageStringFormat = \"pretty\"): string {\n return convertToFormattedString(this, format);\n }\n}\n\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n\n index?: number;\n};\n\nexport function isOpenAIToolCallArray(\n value?: unknown\n): value is OpenAIToolCall[] {\n return (\n Array.isArray(value) &&\n value.every((v) => typeof (v as OpenAIToolCall).index === \"number\")\n );\n}\n\n/**\n * Default keys that should be preserved (not merged) when concatenating message chunks.\n * These are identification and timestamp fields that shouldn't be summed or concatenated.\n */\nexport const DEFAULT_MERGE_IGNORE_KEYS: readonly string[] = [\n \"index\", // Used for identification in tool calls, not accumulation\n \"created\", // Timestamp field\n \"timestamp\", // Timestamp field\n] as const;\n\n/**\n * Options for controlling merge behavior in `_mergeDicts`.\n */\nexport interface MergeDictsOptions {\n /**\n * Keys to ignore during merging. When a key is in this list:\n * - For numeric values: the original value is preserved (not summed)\n * - For string values: the original value is preserved (not concatenated)\n *\n * Defaults to `DEFAULT_MERGE_IGNORE_KEYS` which includes 'index', 'created', 'timestamp'.\n *\n * @example\n * // Extend defaults with custom keys\n * { ignoreKeys: [...DEFAULT_MERGE_IGNORE_KEYS, 'role', 'customField'] }\n */\n ignoreKeys?: readonly string[];\n}\n\nexport function _mergeDicts(\n /**\n * The left dictionary to merge.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n left: Record<string, any> | undefined,\n /**\n * The right dictionary to merge.\n * @type {Record<string, any>}\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n right: Record<string, any> | undefined,\n /**\n * The options for the merge.\n */\n options?: MergeDictsOptions\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> | undefined {\n /**\n * The keys to ignore during merging.\n */\n const ignoreKeys = options?.ignoreKeys ?? DEFAULT_MERGE_IGNORE_KEYS;\n if (left == null && right == null) {\n return undefined;\n }\n if (left == null || right == null) {\n return left ?? right;\n }\n const merged = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (merged[key] == null) {\n merged[key] = value;\n } else if (value == null) {\n continue;\n } else if (\n typeof merged[key] !== typeof value ||\n Array.isArray(merged[key]) !== Array.isArray(value)\n ) {\n throw new Error(\n `field[${key}] already exists in the message chunk, but with a different type.`\n );\n } else if (typeof merged[key] === \"string\") {\n if (key === \"type\") {\n // Do not merge 'type' fields\n continue;\n } else if (\n [\"id\", \"name\", \"output_version\", \"model_provider\"].includes(key)\n ) {\n // Keep the incoming value for these fields if its defined\n if (value) {\n merged[key] = value;\n }\n } else if (ignoreKeys.includes(key)) {\n // Preserve the original value for ignored keys\n continue;\n } else {\n merged[key] += value;\n }\n } else if (typeof merged[key] === \"number\") {\n if (ignoreKeys.includes(key)) {\n // Preserve the original value for ignored keys\n continue;\n }\n merged[key] = merged[key] + value;\n } else if (typeof merged[key] === \"object\" && !Array.isArray(merged[key])) {\n merged[key] = _mergeDicts(merged[key], value, options);\n } else if (Array.isArray(merged[key])) {\n merged[key] = _mergeLists(merged[key], value, options);\n } else if (merged[key] === value) {\n continue;\n } else {\n console.warn(\n `field[${key}] already exists in this message chunk and value has unsupported type.`\n );\n }\n }\n return merged;\n}\n\nfunction isMergeableIndex(index: unknown): index is number | string {\n return typeof index === \"number\" || typeof index === \"string\";\n}\n\nfunction hasMergeableIndex(\n value: unknown\n): value is { index: number | string } {\n if (typeof value !== \"object\" || value === null) return false;\n if (!(\"index\" in value)) return false;\n return isMergeableIndex(value.index);\n}\n\nfunction hasMergeableId(value: unknown): value is { id: string | number } {\n if (typeof value !== \"object\" || value === null) return false;\n if (!(\"id\" in value)) return false;\n const id = (value as Record<string, unknown>).id;\n return id != null && id !== \"\";\n}\n\nfunction getMergeableTypeBase(type: string): string {\n return type.endsWith(\"_delta\") ? type.slice(0, -\"_delta\".length) : type;\n}\n\nfunction hasMismatchedMergeableType(left: unknown, right: unknown): boolean {\n if (typeof left !== \"object\" || left === null) return false;\n if (typeof right !== \"object\" || right === null) return false;\n if (!(\"type\" in left) || !(\"type\" in right)) return false;\n\n return (\n typeof left.type === \"string\" &&\n typeof right.type === \"string\" &&\n getMergeableTypeBase(left.type) !== getMergeableTypeBase(right.type)\n );\n}\n\n/**\n * Find the index of an existing item in `merged` that should be merged with\n * `item`, based on index and/or id matching.\n *\n * Matching priority:\n * 1. Both have index → match on index (+ id when both present)\n * 2. Neither has index, both have id → match on id alone\n * 3. Otherwise → no match (item should be appended)\n */\nfunction _findMergeTarget<Content extends ContentBlock>(\n merged: Content[],\n item: Content\n): number {\n const itemHasIndex = hasMergeableIndex(item);\n const itemHasId = hasMergeableId(item);\n\n if (!itemHasIndex && !itemHasId) return -1;\n\n return merged.findIndex((leftItem) => {\n const leftHasIndex = hasMergeableIndex(leftItem);\n const leftHasId = hasMergeableId(leftItem);\n\n if (itemHasIndex && leftHasIndex) {\n // Both have index: match on index, with id as tiebreaker\n const indicesMatch = leftItem.index === item.index;\n if (!indicesMatch) return false;\n if (hasMismatchedMergeableType(leftItem, item)) return false;\n if (leftHasId && itemHasId) return leftItem.id === item.id;\n return true; // indices match, one or both missing id\n }\n\n if (!itemHasIndex && !leftHasIndex && itemHasId && leftHasId) {\n // Neither has index: fall back to id-only matching. Handles providers\n // that don't include `index` on streaming tool call deltas.\n return leftItem.id === item.id;\n }\n\n return false;\n });\n}\n\nexport function _mergeLists<Content extends ContentBlock>(\n left?: Content[],\n right?: Content[],\n options?: MergeDictsOptions\n): Content[] | undefined {\n if (left == null && right == null) {\n return undefined;\n } else if (left == null || right == null) {\n return left || right;\n } else {\n const merged = [...left];\n for (const item of right) {\n const toMerge = _findMergeTarget(merged, item);\n if (toMerge !== -1) {\n merged[toMerge] = _mergeDicts(\n merged[toMerge],\n item,\n options\n ) as Content;\n } else if (\n typeof item === \"object\" &&\n item !== null &&\n \"text\" in item &&\n item.text === \"\"\n ) {\n continue;\n } else {\n merged.push(item);\n }\n }\n return merged;\n }\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _mergeObj<T = any>(\n left: T | undefined,\n right: T | undefined,\n options?: MergeDictsOptions\n): T | undefined {\n if (left == null && right == null) {\n return undefined;\n }\n if (left == null || right == null) {\n return left ?? right;\n } else if (typeof left !== typeof right) {\n throw new Error(\n `Cannot merge objects of different types.\\nLeft ${typeof left}\\nRight ${typeof right}`\n );\n } else if (typeof left === \"string\" && typeof right === \"string\") {\n return (left + right) as T;\n } else if (Array.isArray(left) && Array.isArray(right)) {\n return _mergeLists(left, right, options) as T;\n } else if (typeof left === \"object\" && typeof right === \"object\") {\n return _mergeDicts(\n left as Record<string, unknown>,\n right as Record<string, unknown>,\n options\n ) as T;\n } else if (left === right) {\n return left;\n } else {\n throw new Error(\n `Can not merge objects of different types.\\nLeft ${left}\\nRight ${right}`\n );\n }\n}\n\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport abstract class BaseMessageChunk<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n\n static isInstance(obj: unknown): obj is BaseMessageChunk {\n if (!super.isInstance(obj)) {\n return false;\n }\n // Check if obj is an instance of BaseMessageChunk by traversing the prototype chain\n let proto = Object.getPrototypeOf(obj);\n while (proto !== null) {\n if (proto === BaseMessageChunk.prototype) {\n return true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n }\n\n static [Symbol.hasInstance](obj: unknown) {\n return this.isInstance(obj);\n }\n}\n\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\n\nexport function _isMessageFieldWithRole(\n x: BaseMessageLike\n): x is MessageFieldWithRole {\n return typeof (x as MessageFieldWithRole).role === \"string\";\n}\n\nexport type BaseMessageLike =\n | BaseMessage\n | MessageFieldWithRole\n | [MessageType, MessageContent]\n | string\n /**\n * Serialized form of {@link RemoveMessage}. At runtime,\n * {@link coerceMessageLikeToMessage} converts this to a `RemoveMessage`\n * instance which the `add_messages` reducer uses to delete messages by ID.\n */\n | { type: \"remove\"; id: string }\n /**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n } & BaseMessageFields &\n Record<string, unknown>)\n | SerializedConstructor;\n\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport function isBaseMessage(\n messageLike?: unknown\n): messageLike is BaseMessage {\n return typeof (messageLike as BaseMessage)?._getType === \"function\";\n}\n\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport function isBaseMessageChunk(\n messageLike?: unknown\n): messageLike is BaseMessageChunk {\n return BaseMessageChunk.isInstance(messageLike);\n}\n"],"mappings":";;;;;;;;;AAoBA,MAAM,iBAAyB,OAAO,IAAI,mBAAmB;;;;;;AA0E7D,SAAS,gCACP,cACgB;CAChB,IAAI,MAAM,QAAQ,YAAY,GAC5B,OAAO;CAET,IAAI,OAAO,iBAAiB,UAC1B,OAAO,iBAAiB,KAAK,CAAC,IAAI,CAAC;EAAE,MAAM;EAAQ,MAAM;CAAa,CAAC;CAEzE,IAAI,gBAAgB,MAClB,OAAO,CAAC;CAEV,OAAO,CAAC,YAA4B;AACtC;AAEA,SAAgB,aACd,cACA,eACgB;CAEhB,IAAI,OAAO,iBAAiB,UAAU;EACpC,IAAI,iBAAiB,IACnB,OAAO;EAET,IAAI,OAAO,kBAAkB,UAC3B,OAAO,eAAe;OACjB,IAAI,MAAM,QAAQ,aAAa,KAAK,cAAc,WAAW,GAClE,OAAO;OACF,IACL,MAAM,QAAQ,aAAa,KAC3B,cAAc,MAAM,MAAMA,aAAAA,mBAAmB,CAAC,CAAC,GAE/C,OAAO,CACL;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR,GACA,GAAG,aACL;OAEA,OAAO,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAa,GAAG,GAAG,aAAa;CAGlE,OAAO,IAAI,MAAM,QAAQ,aAAa,GAAG;EACvC,MAAM,OAAO,gCAAgC,YAAY;EACzD,OAAO,YAAY,MAAM,aAAa,KAAK,CAAC,GAAG,MAAM,GAAG,aAAa;CACvE,OACE,IAAI,kBAAkB,IACpB,OAAO;MACF,IACL,MAAM,QAAQ,YAAY,KAC1B,aAAa,MAAM,MAAMA,aAAAA,mBAAmB,CAAC,CAAC,GAE9C,OAAO,CACL,GAAG,cACH;EACE,MAA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;CAEF,IAAI,QAAQ,QAAQ,SAAS,MAC3B,OAAO,QAAQ;MACV,IAAI,OAAO,SAAS,OAAO,OAChC,MAAM,IAAI,MACR,kDAAkD,OAAO,KAAK,UAAU,OAAO,OACjF;MACK,IAAI,OAAO,SAAS,YAAY,OAAO,UAAU,UACtD,OAAQ,OAAO;MACV,IAAI,MAAM,QAAQ,IAAI,KAAK,MAAM,QAAQ,KAAK,GACnD,OAAO,YAAY,MAAM,OAAO,OAAO;MAClC,IAAI,OAAO,SAAS,YAAY,OAAO,UAAU,UACtD,OAAO,YACL,MACA,OACA,OACF;MACK,IAAI,SAAS,OAClB,OAAO;MAEP,MAAM,IAAI,MACR,mDAAmD,KAAK,UAAU,OACpE;AAEJ;;;;;;;;AASA,IAAsB,mBAAtB,MAAsB,yBAGZ,YAA+B;CAGvC,OAAO,WAAW,KAAuC;EACvD,IAAI,CAAC,MAAM,WAAW,GAAG,GACvB,OAAO;EAGT,IAAI,QAAQ,OAAO,eAAe,GAAG;EACrC,OAAO,UAAU,MAAM;GACrB,IAAI,UAAU,iBAAiB,WAC7B,OAAO;GAET,QAAQ,OAAO,eAAe,KAAK;EACrC;EACA,OAAO;CACT;CAEA,QAAQ,OAAO,aAAa,KAAc;EACxC,OAAO,KAAK,WAAW,GAAG;CAC5B;AACF;AAQA,SAAgB,wBACd,GAC2B;CAC3B,OAAO,OAAQ,EAA2B,SAAS;AACrD;;;;AAyBA,SAAgB,cACd,aAC4B;CAC5B,OAAO,OAAQ,aAA6B,aAAa;AAC3D;;;;AAKA,SAAgB,mBACd,aACiC;CACjC,OAAO,iBAAiB,WAAW,WAAW;AAChD"}
1
+ {"version":3,"file":"base.cjs","names":["isDataContentBlock","Serializable","convertToV1FromDataContent","convertToV1FromChatCompletionsInput","convertToV1FromAnthropicInput","isMessage","convertToFormattedString"],"sources":["../../src/messages/base.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { isDataContentBlock } from \"./content/data.js\";\nimport { convertToV1FromAnthropicInput } from \"./block_translators/anthropic.js\";\nimport { convertToV1FromDataContent } from \"./block_translators/data.js\";\nimport { convertToV1FromChatCompletionsInput } from \"./block_translators/openai.js\";\nimport {\n $InferMessageContent,\n $InferResponseMetadata,\n MessageStructure,\n MessageType,\n isMessage,\n Message,\n} from \"./message.js\";\nimport {\n convertToFormattedString,\n type MessageStringFormat,\n} from \"./format.js\";\n\n/** @internal */\nconst MESSAGE_SYMBOL: symbol = Symbol.for(\"langchain.message\");\n\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n response_metadata?: Record<string, any>;\n id?: string;\n}\n\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\n\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\n\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\n\nexport type MessageContent = string | Array<ContentBlock>;\n\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n}\n\nexport type BaseMessageFields<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n> = Pick<Message, \"id\" | \"name\"> & {\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\n\n/**\n * Normalize non-string `firstContent` to a block array for merge/spread.\n * Some serializers (e.g. Anthropic-style) yield a single block object instead of a one-element array;\n * spreading that object as an array throws (\"is not iterable\").\n */\nfunction contentBlocksFromNonStringFirst(\n firstContent: MessageContent\n): ContentBlock[] {\n if (Array.isArray(firstContent)) {\n return firstContent;\n }\n if (typeof firstContent === \"string\") {\n return firstContent === \"\" ? [] : [{ type: \"text\", text: firstContent }];\n }\n if (firstContent == null) {\n return [];\n }\n return [firstContent as ContentBlock];\n}\n\nexport function mergeContent(\n firstContent: MessageContent,\n secondContent: MessageContent\n): MessageContent {\n // If first content is a string\n if (typeof firstContent === \"string\") {\n if (firstContent === \"\") {\n return secondContent;\n }\n if (typeof secondContent === \"string\") {\n return firstContent + secondContent;\n } else if (Array.isArray(secondContent) && secondContent.length === 0) {\n return firstContent;\n } else if (\n Array.isArray(secondContent) &&\n secondContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n {\n type: \"text\",\n source_type: \"text\",\n text: firstContent,\n },\n ...secondContent,\n ];\n } else {\n return [{ type: \"text\", text: firstContent }, ...secondContent];\n }\n // If both are arrays\n } else if (Array.isArray(secondContent)) {\n const left = contentBlocksFromNonStringFirst(firstContent);\n return _mergeLists(left, secondContent) ?? [...left, ...secondContent];\n } else {\n if (secondContent === \"\") {\n return firstContent;\n } else if (\n Array.isArray(firstContent) &&\n firstContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n ...firstContent,\n {\n type: \"file\",\n source_type: \"text\",\n text: secondContent,\n },\n ];\n } else {\n const left = contentBlocksFromNonStringFirst(firstContent);\n return [...left, { type: \"text\", text: secondContent }];\n }\n }\n}\n\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport function _mergeStatus(\n left?: \"success\" | \"error\",\n right?: \"success\" | \"error\"\n): \"success\" | \"error\" | undefined {\n if (left === \"error\" || right === \"error\") {\n return \"error\";\n }\n return \"success\";\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringifyWithDepthLimit(obj: any, depthLimit: number): string {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n function helper(obj: any, currentDepth: number): any {\n if (typeof obj !== \"object\" || obj === null || obj === undefined) {\n return obj;\n }\n if (currentDepth >= depthLimit) {\n if (Array.isArray(obj)) {\n return \"[Array]\";\n }\n return \"[Object]\";\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => helper(item, currentDepth + 1));\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = helper(obj[key], currentDepth + 1);\n }\n return result;\n }\n\n return JSON.stringify(helper(obj, 0), null, 2);\n}\n\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport abstract class BaseMessage<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n>\n extends Serializable\n implements Message<TStructure, TRole>\n{\n lc_namespace = [\"langchain_core\", \"messages\"];\n\n lc_serializable = true;\n\n get lc_aliases(): Record<string, string> {\n // exclude snake case conversion to pascal case\n return {\n additional_kwargs: \"additional_kwargs\",\n response_metadata: \"response_metadata\",\n };\n }\n\n readonly [MESSAGE_SYMBOL] = true as const;\n\n abstract readonly type: TRole;\n\n id?: string;\n\n /** @inheritdoc */\n name?: string;\n\n content: $InferMessageContent<TStructure, TRole>;\n\n additional_kwargs: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]\n >;\n\n response_metadata: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"response_metadata\"]\n >;\n\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType {\n return this.type;\n }\n\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType {\n return this._getType();\n }\n\n constructor(\n arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>\n ) {\n const fields: BaseMessageFields<TStructure, TRole> =\n typeof arg === \"string\" || Array.isArray(arg)\n ? ({ content: arg } as BaseMessageFields<TStructure, TRole>)\n : arg;\n if (!fields.additional_kwargs) {\n fields.additional_kwargs = {};\n }\n if (!fields.response_metadata) {\n fields.response_metadata = {};\n }\n super(fields);\n this.name = fields.name;\n if (fields.content === undefined && fields.contentBlocks !== undefined) {\n this.content = fields.contentBlocks as $InferMessageContent<\n TStructure,\n TRole\n >;\n this.response_metadata = {\n output_version: \"v1\",\n ...fields.response_metadata,\n };\n } else if (fields.content !== undefined) {\n this.content = fields.content ?? [];\n this.response_metadata = fields.response_metadata;\n } else {\n this.content = [] as $InferMessageContent<TStructure, TRole>;\n this.response_metadata = fields.response_metadata;\n }\n this.additional_kwargs = fields.additional_kwargs;\n this.id = fields.id;\n }\n\n /** Get text content of the message. */\n get text(): string {\n const textBlocks: ContentBlock.Text[] = this.contentBlocks.filter(\n (block: ContentBlock.Standard) => block.type === \"text\"\n );\n return textBlocks.reduce(\n (acc: string, block: ContentBlock.Text) => acc + (block.text ?? \"\"),\n \"\"\n );\n }\n\n get contentBlocks(): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock> =\n typeof this.content === \"string\"\n ? [{ type: \"text\", text: this.content }]\n : this.content;\n const parsingSteps = [\n convertToV1FromDataContent,\n convertToV1FromChatCompletionsInput,\n convertToV1FromAnthropicInput,\n ];\n const parsedBlocks = parsingSteps.reduce(\n (blocks, step) => step(blocks),\n blocks\n );\n return parsedBlocks as Array<ContentBlock.Standard>;\n }\n\n toDict(): StoredMessage {\n return {\n type: this.getType(),\n data: (this.toJSON() as SerializedConstructor)\n .kwargs as StoredMessageData,\n };\n }\n\n static lc_name() {\n return \"BaseMessage\";\n }\n\n // Can't be protected for silly reasons\n get _printableFields(): Record<string, unknown> {\n return {\n id: this.id,\n content: this.content,\n name: this.name,\n additional_kwargs: this.additional_kwargs,\n response_metadata: this.response_metadata,\n };\n }\n\n static isInstance(obj: unknown): obj is BaseMessage {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n MESSAGE_SYMBOL in obj &&\n (obj as Record<symbol, unknown>)[MESSAGE_SYMBOL] === true &&\n isMessage(obj)\n );\n }\n\n static [Symbol.hasInstance](obj: unknown) {\n return this.isInstance(obj);\n }\n\n // this private method is used to update the ID for the runtime\n // value as well as in lc_kwargs for serialisation\n _updateId(value: string | undefined) {\n this.id = value;\n\n // lc_attributes wouldn't work here, because jest compares the\n // whole object\n this.lc_kwargs.id = value;\n }\n\n get [Symbol.toStringTag]() {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.constructor as any).lc_name();\n }\n\n // Override the default behavior of console.log\n [Symbol.for(\"nodejs.util.inspect.custom\")](depth: number | null) {\n if (depth === null) {\n return this;\n }\n const printable = stringifyWithDepthLimit(\n this._printableFields,\n Math.max(4, depth)\n );\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return `${(this.constructor as any).lc_name()} ${printable}`;\n }\n\n toFormattedString(format: MessageStringFormat = \"pretty\"): string {\n return convertToFormattedString(this, format);\n }\n}\n\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n\n index?: number;\n};\n\nexport function isOpenAIToolCallArray(\n value?: unknown\n): value is OpenAIToolCall[] {\n return (\n Array.isArray(value) &&\n value.every((v) => typeof (v as OpenAIToolCall).index === \"number\")\n );\n}\n\n/**\n * Default keys that should be preserved (not merged) when concatenating message chunks.\n * These are identification and timestamp fields that shouldn't be summed or concatenated.\n */\nexport const DEFAULT_MERGE_IGNORE_KEYS: readonly string[] = [\n \"index\", // Used for identification in tool calls, not accumulation\n \"created\", // Timestamp field\n \"timestamp\", // Timestamp field\n] as const;\n\n/**\n * Options for controlling merge behavior in `_mergeDicts`.\n */\nexport interface MergeDictsOptions {\n /**\n * Keys to ignore during merging. When a key is in this list:\n * - For numeric values: the original value is preserved (not summed)\n * - For string values: the original value is preserved (not concatenated)\n *\n * Defaults to `DEFAULT_MERGE_IGNORE_KEYS` which includes 'index', 'created', 'timestamp'.\n *\n * @example\n * // Extend defaults with custom keys\n * { ignoreKeys: [...DEFAULT_MERGE_IGNORE_KEYS, 'role', 'customField'] }\n */\n ignoreKeys?: readonly string[];\n}\n\nexport function _mergeDicts(\n /**\n * The left dictionary to merge.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n left: Record<string, any> | undefined,\n /**\n * The right dictionary to merge.\n * @type {Record<string, any>}\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n right: Record<string, any> | undefined,\n /**\n * The options for the merge.\n */\n options?: MergeDictsOptions\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> | undefined {\n /**\n * The keys to ignore during merging.\n */\n const ignoreKeys = options?.ignoreKeys ?? DEFAULT_MERGE_IGNORE_KEYS;\n if (left == null && right == null) {\n return undefined;\n }\n if (left == null || right == null) {\n return left ?? right;\n }\n const merged = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (merged[key] == null) {\n merged[key] = value;\n } else if (value == null) {\n continue;\n } else if (\n typeof merged[key] !== typeof value ||\n Array.isArray(merged[key]) !== Array.isArray(value)\n ) {\n throw new Error(\n `field[${key}] already exists in the message chunk, but with a different type.`\n );\n } else if (typeof merged[key] === \"string\") {\n if (key === \"type\") {\n // Do not merge 'type' fields\n continue;\n } else if (\n [\"id\", \"name\", \"output_version\", \"model_provider\"].includes(key)\n ) {\n // Keep the incoming value for these fields if its defined\n if (value) {\n merged[key] = value;\n }\n } else if (ignoreKeys.includes(key)) {\n // Preserve the original value for ignored keys\n continue;\n } else {\n merged[key] += value;\n }\n } else if (typeof merged[key] === \"number\") {\n if (ignoreKeys.includes(key)) {\n // Preserve the original value for ignored keys\n continue;\n }\n merged[key] = merged[key] + value;\n } else if (typeof merged[key] === \"object\" && !Array.isArray(merged[key])) {\n merged[key] = _mergeDicts(merged[key], value, options);\n } else if (Array.isArray(merged[key])) {\n merged[key] = _mergeLists(merged[key], value, options);\n } else if (merged[key] === value) {\n continue;\n } else {\n console.warn(\n `field[${key}] already exists in this message chunk and value has unsupported type.`\n );\n }\n }\n return merged;\n}\n\nfunction isMergeableIndex(index: unknown): index is number | string {\n return typeof index === \"number\" || typeof index === \"string\";\n}\n\nfunction hasMergeableIndex(\n value: unknown\n): value is { index: number | string } {\n if (typeof value !== \"object\" || value === null) return false;\n if (!(\"index\" in value)) return false;\n return isMergeableIndex(value.index);\n}\n\nfunction hasMergeableId(value: unknown): value is { id: string | number } {\n if (typeof value !== \"object\" || value === null) return false;\n if (!(\"id\" in value)) return false;\n const id = (value as Record<string, unknown>).id;\n return id != null && id !== \"\";\n}\n\nfunction getMergeableTypeBase(type: string): string {\n return type.endsWith(\"_delta\") ? type.slice(0, -\"_delta\".length) : type;\n}\n\nfunction hasMismatchedMergeableType(left: unknown, right: unknown): boolean {\n if (typeof left !== \"object\" || left === null) return false;\n if (typeof right !== \"object\" || right === null) return false;\n if (!(\"type\" in left) || !(\"type\" in right)) return false;\n\n return (\n typeof left.type === \"string\" &&\n typeof right.type === \"string\" &&\n getMergeableTypeBase(left.type) !== getMergeableTypeBase(right.type)\n );\n}\n\n/**\n * Find the index of an existing item in `merged` that should be merged with\n * `item`, based on index and/or id matching.\n *\n * Matching priority:\n * 1. Both have index → match on index (+ id when both present)\n * 2. Neither has index, both have id → match on id alone\n * 3. Otherwise → no match (item should be appended)\n */\nfunction _findMergeTarget<Content extends ContentBlock>(\n merged: Content[],\n item: Content\n): number {\n const itemHasIndex = hasMergeableIndex(item);\n const itemHasId = hasMergeableId(item);\n\n if (!itemHasIndex && !itemHasId) return -1;\n\n return merged.findIndex((leftItem) => {\n const leftHasIndex = hasMergeableIndex(leftItem);\n const leftHasId = hasMergeableId(leftItem);\n\n if (itemHasIndex && leftHasIndex) {\n // Both have index: match on index, with id as tiebreaker\n const indicesMatch = leftItem.index === item.index;\n if (!indicesMatch) return false;\n if (hasMismatchedMergeableType(leftItem, item)) return false;\n if (leftHasId && itemHasId) return leftItem.id === item.id;\n return true; // indices match, one or both missing id\n }\n\n if (!itemHasIndex && !leftHasIndex && itemHasId && leftHasId) {\n // Neither has index: fall back to id-only matching. Handles providers\n // that don't include `index` on streaming tool call deltas.\n return leftItem.id === item.id;\n }\n\n return false;\n });\n}\n\nexport function _mergeLists<Content extends ContentBlock>(\n left?: Content[],\n right?: Content[],\n options?: MergeDictsOptions\n): Content[] | undefined {\n if (left == null && right == null) {\n return undefined;\n } else if (left == null || right == null) {\n return left || right;\n } else {\n const merged = [...left];\n for (const item of right) {\n const toMerge = _findMergeTarget(merged, item);\n if (toMerge !== -1) {\n merged[toMerge] = _mergeDicts(\n merged[toMerge],\n item,\n options\n ) as Content;\n } else if (\n typeof item === \"object\" &&\n item !== null &&\n \"text\" in item &&\n item.text === \"\"\n ) {\n continue;\n } else {\n merged.push(item);\n }\n }\n return merged;\n }\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _mergeObj<T = any>(\n left: T | undefined,\n right: T | undefined,\n options?: MergeDictsOptions\n): T | undefined {\n if (left == null && right == null) {\n return undefined;\n }\n if (left == null || right == null) {\n return left ?? right;\n } else if (typeof left !== typeof right) {\n throw new Error(\n `Cannot merge objects of different types.\\nLeft ${typeof left}\\nRight ${typeof right}`\n );\n } else if (typeof left === \"string\" && typeof right === \"string\") {\n return (left + right) as T;\n } else if (Array.isArray(left) && Array.isArray(right)) {\n return _mergeLists(left, right, options) as T;\n } else if (typeof left === \"object\" && typeof right === \"object\") {\n return _mergeDicts(\n left as Record<string, unknown>,\n right as Record<string, unknown>,\n options\n ) as T;\n } else if (left === right) {\n return left;\n } else {\n throw new Error(\n `Can not merge objects of different types.\\nLeft ${left}\\nRight ${right}`\n );\n }\n}\n\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport abstract class BaseMessageChunk<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n\n static isInstance(obj: unknown): obj is BaseMessageChunk {\n if (!super.isInstance(obj)) {\n return false;\n }\n // Check if obj is an instance of BaseMessageChunk by traversing the prototype chain\n let proto = Object.getPrototypeOf(obj);\n while (proto !== null) {\n if (proto === BaseMessageChunk.prototype) {\n return true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n }\n\n static [Symbol.hasInstance](obj: unknown) {\n return this.isInstance(obj);\n }\n}\n\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\n\nexport function _isMessageFieldWithRole(\n x: BaseMessageLike\n): x is MessageFieldWithRole {\n return typeof (x as MessageFieldWithRole).role === \"string\";\n}\n\nexport type BaseMessageLike =\n | BaseMessage\n | MessageFieldWithRole\n | [MessageType, MessageContent]\n | string\n /**\n * Serialized form of {@link RemoveMessage}. At runtime,\n * {@link coerceMessageLikeToMessage} converts this to a `RemoveMessage`\n * instance which the `add_messages` reducer uses to delete messages by ID.\n */\n | { type: \"remove\"; id: string }\n /**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n } & BaseMessageFields &\n Record<string, unknown>)\n | SerializedConstructor;\n\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport function isBaseMessage(\n messageLike?: unknown\n): messageLike is BaseMessage {\n return typeof (messageLike as BaseMessage)?._getType === \"function\";\n}\n\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport function isBaseMessageChunk(\n messageLike?: unknown\n): messageLike is BaseMessageChunk {\n return BaseMessageChunk.isInstance(messageLike);\n}\n"],"mappings":";;;;;;;;;AAoBA,MAAM,iBAAyB,OAAO,IAAI,mBAAmB;;;;;;AA0E7D,SAAS,gCACP,cACgB;CAChB,IAAI,MAAM,QAAQ,YAAY,GAC5B,OAAO;CAET,IAAI,OAAO,iBAAiB,UAC1B,OAAO,iBAAiB,KAAK,CAAC,IAAI,CAAC;EAAE,MAAM;EAAQ,MAAM;CAAa,CAAC;CAEzE,IAAI,gBAAgB,MAClB,OAAO,CAAC;CAEV,OAAO,CAAC,YAA4B;AACtC;AAEA,SAAgB,aACd,cACA,eACgB;CAEhB,IAAI,OAAO,iBAAiB,UAAU;EACpC,IAAI,iBAAiB,IACnB,OAAO;EAET,IAAI,OAAO,kBAAkB,UAC3B,OAAO,eAAe;OACjB,IAAI,MAAM,QAAQ,aAAa,KAAK,cAAc,WAAW,GAClE,OAAO;OACF,IACL,MAAM,QAAQ,aAAa,KAC3B,cAAc,MAAM,MAAMA,aAAAA,mBAAmB,CAAC,CAAC,GAE/C,OAAO,CACL;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR,GACA,GAAG,aACL;OAEA,OAAO,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAa,GAAG,GAAG,aAAa;CAGlE,OAAO,IAAI,MAAM,QAAQ,aAAa,GAAG;EACvC,MAAM,OAAO,gCAAgC,YAAY;EACzD,OAAO,YAAY,MAAM,aAAa,KAAK,CAAC,GAAG,MAAM,GAAG,aAAa;CACvE,OACE,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UAUhC,OAAO,aAAa,eAAY,OAAA,YAAA,iBAVA,iBAUA;EAMxC,UAAU;OAQL,OAAO;EAkBZ,kBAAkB,SAAQ;;;;;KAQhB;;;;EAIV;;;;EAKA,UAAU;;;;EAKV;EAEA;;iBAGc,sBACd,kBACC,SAAS;;;;;cAWC;;;;UASI;;;;;;;;;;;;EAYf;;iBAGc,YAKd;;;;AAAA,MAAM,iCAMN;;;;;AAAA,OAAO,iCAIP;;;;AAAA,UAAU,oBAET;iBA0Ia,YAAY,gBAAgB,cAC1C,OAAO,WACP,QAAQ,WACR,UAAU,oBACT;iBA+Ba,UAAU,SACxB,MAAM,eACN,OAAO,eACP,UAAU,oBACT;;;;;;;;uBAoCmB,iBACpB,mBAAmB,mBAAmB,kBACtC,cAAc,cAAc,qBACpB,YAAY,YAAY;WACvB,OAAO,OAAO,mBAAmB,iBAAiB,YAAY;SAEhE,WAAW,eAAe,OAAO;UAehC,OAAO,aAAa,eAAY,OAAA,iBAAA,iBAfA,iBAeA;;KAK9B;EACV,MAAM;EACN,SAAS;EACT;IACE;iBAEY,wBACd,GAAG,kBACF,KAAK;KAII,kBACR,cACA,wBACC,aAAa;;;;;;;EAOZ;EAAgB;;;;;;EAKhB,MAAM;IACJ,oBACF,2BACF;;;;iBAKY,cACd,wBACC,eAAe;;;;iBAOF,mBACd,wBACC,eAAe"}
@@ -142,13 +142,7 @@ var BaseMessage = class extends Serializable {
142
142
  }
143
143
  /** Get text content of the message. */
144
144
  get text() {
145
- if (typeof this.content === "string") return this.content;
146
- if (!Array.isArray(this.content)) return "";
147
- return this.content.map((c) => {
148
- if (typeof c === "string") return c;
149
- if (c.type === "text") return c.text;
150
- return "";
151
- }).join("");
145
+ return this.contentBlocks.filter((block) => block.type === "text").reduce((acc, block) => acc + (block.text ?? ""), "");
152
146
  }
153
147
  get contentBlocks() {
154
148
  const blocks = typeof this.content === "string" ? [{
@@ -224,17 +218,18 @@ function _mergeDicts(left, right, options) {
224
218
  for (const [key, value] of Object.entries(right)) if (merged[key] == null) merged[key] = value;
225
219
  else if (value == null) continue;
226
220
  else if (typeof merged[key] !== typeof value || Array.isArray(merged[key]) !== Array.isArray(value)) throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`);
227
- else if (typeof merged[key] === "string") if (key === "type") continue;
228
- else if ([
229
- "id",
230
- "name",
231
- "output_version",
232
- "model_provider"
233
- ].includes(key)) {
234
- if (value) merged[key] = value;
235
- } else if (ignoreKeys.includes(key)) continue;
236
- else merged[key] += value;
237
- else if (typeof merged[key] === "number") {
221
+ else if (typeof merged[key] === "string") {
222
+ if (key === "type") continue;
223
+ else if ([
224
+ "id",
225
+ "name",
226
+ "output_version",
227
+ "model_provider"
228
+ ].includes(key)) {
229
+ if (value) merged[key] = value;
230
+ } else if (ignoreKeys.includes(key)) continue;
231
+ else merged[key] += value;
232
+ } else if (typeof merged[key] === "number") {
238
233
  if (ignoreKeys.includes(key)) continue;
239
234
  merged[key] = merged[key] + value;
240
235
  } else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) merged[key] = _mergeDicts(merged[key], value, options);
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../src/messages/base.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { isDataContentBlock } from \"./content/data.js\";\nimport { convertToV1FromAnthropicInput } from \"./block_translators/anthropic.js\";\nimport { convertToV1FromDataContent } from \"./block_translators/data.js\";\nimport { convertToV1FromChatCompletionsInput } from \"./block_translators/openai.js\";\nimport {\n $InferMessageContent,\n $InferResponseMetadata,\n MessageStructure,\n MessageType,\n isMessage,\n Message,\n} from \"./message.js\";\nimport {\n convertToFormattedString,\n type MessageStringFormat,\n} from \"./format.js\";\n\n/** @internal */\nconst MESSAGE_SYMBOL: symbol = Symbol.for(\"langchain.message\");\n\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n response_metadata?: Record<string, any>;\n id?: string;\n}\n\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\n\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\n\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\n\nexport type MessageContent = string | Array<ContentBlock>;\n\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n}\n\nexport type BaseMessageFields<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n> = Pick<Message, \"id\" | \"name\"> & {\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\n\n/**\n * Normalize non-string `firstContent` to a block array for merge/spread.\n * Some serializers (e.g. Anthropic-style) yield a single block object instead of a one-element array;\n * spreading that object as an array throws (\"is not iterable\").\n */\nfunction contentBlocksFromNonStringFirst(\n firstContent: MessageContent\n): ContentBlock[] {\n if (Array.isArray(firstContent)) {\n return firstContent;\n }\n if (typeof firstContent === \"string\") {\n return firstContent === \"\" ? [] : [{ type: \"text\", text: firstContent }];\n }\n if (firstContent == null) {\n return [];\n }\n return [firstContent as ContentBlock];\n}\n\nexport function mergeContent(\n firstContent: MessageContent,\n secondContent: MessageContent\n): MessageContent {\n // If first content is a string\n if (typeof firstContent === \"string\") {\n if (firstContent === \"\") {\n return secondContent;\n }\n if (typeof secondContent === \"string\") {\n return firstContent + secondContent;\n } else if (Array.isArray(secondContent) && secondContent.length === 0) {\n return firstContent;\n } else if (\n Array.isArray(secondContent) &&\n secondContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n {\n type: \"text\",\n source_type: \"text\",\n text: firstContent,\n },\n ...secondContent,\n ];\n } else {\n return [{ type: \"text\", text: firstContent }, ...secondContent];\n }\n // If both are arrays\n } else if (Array.isArray(secondContent)) {\n const left = contentBlocksFromNonStringFirst(firstContent);\n return _mergeLists(left, secondContent) ?? [...left, ...secondContent];\n } else {\n if (secondContent === \"\") {\n return firstContent;\n } else if (\n Array.isArray(firstContent) &&\n firstContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n ...firstContent,\n {\n type: \"file\",\n source_type: \"text\",\n text: secondContent,\n },\n ];\n } else {\n const left = contentBlocksFromNonStringFirst(firstContent);\n return [...left, { type: \"text\", text: secondContent }];\n }\n }\n}\n\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport function _mergeStatus(\n left?: \"success\" | \"error\",\n right?: \"success\" | \"error\"\n): \"success\" | \"error\" | undefined {\n if (left === \"error\" || right === \"error\") {\n return \"error\";\n }\n return \"success\";\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringifyWithDepthLimit(obj: any, depthLimit: number): string {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n function helper(obj: any, currentDepth: number): any {\n if (typeof obj !== \"object\" || obj === null || obj === undefined) {\n return obj;\n }\n if (currentDepth >= depthLimit) {\n if (Array.isArray(obj)) {\n return \"[Array]\";\n }\n return \"[Object]\";\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => helper(item, currentDepth + 1));\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = helper(obj[key], currentDepth + 1);\n }\n return result;\n }\n\n return JSON.stringify(helper(obj, 0), null, 2);\n}\n\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport abstract class BaseMessage<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n>\n extends Serializable\n implements Message<TStructure, TRole>\n{\n lc_namespace = [\"langchain_core\", \"messages\"];\n\n lc_serializable = true;\n\n get lc_aliases(): Record<string, string> {\n // exclude snake case conversion to pascal case\n return {\n additional_kwargs: \"additional_kwargs\",\n response_metadata: \"response_metadata\",\n };\n }\n\n readonly [MESSAGE_SYMBOL] = true as const;\n\n abstract readonly type: TRole;\n\n id?: string;\n\n /** @inheritdoc */\n name?: string;\n\n content: $InferMessageContent<TStructure, TRole>;\n\n additional_kwargs: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]\n >;\n\n response_metadata: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"response_metadata\"]\n >;\n\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType {\n return this.type;\n }\n\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType {\n return this._getType();\n }\n\n constructor(\n arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>\n ) {\n const fields: BaseMessageFields<TStructure, TRole> =\n typeof arg === \"string\" || Array.isArray(arg)\n ? ({ content: arg } as BaseMessageFields<TStructure, TRole>)\n : arg;\n if (!fields.additional_kwargs) {\n fields.additional_kwargs = {};\n }\n if (!fields.response_metadata) {\n fields.response_metadata = {};\n }\n super(fields);\n this.name = fields.name;\n if (fields.content === undefined && fields.contentBlocks !== undefined) {\n this.content = fields.contentBlocks as $InferMessageContent<\n TStructure,\n TRole\n >;\n this.response_metadata = {\n output_version: \"v1\",\n ...fields.response_metadata,\n };\n } else if (fields.content !== undefined) {\n this.content = fields.content ?? [];\n this.response_metadata = fields.response_metadata;\n } else {\n this.content = [] as $InferMessageContent<TStructure, TRole>;\n this.response_metadata = fields.response_metadata;\n }\n this.additional_kwargs = fields.additional_kwargs;\n this.id = fields.id;\n }\n\n /** Get text content of the message. */\n get text(): string {\n if (typeof this.content === \"string\") {\n return this.content;\n }\n if (!Array.isArray(this.content)) return \"\";\n return this.content\n .map((c) => {\n if (typeof c === \"string\") return c;\n if (c.type === \"text\") return c.text;\n return \"\";\n })\n .join(\"\");\n }\n\n get contentBlocks(): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock> =\n typeof this.content === \"string\"\n ? [{ type: \"text\", text: this.content }]\n : this.content;\n const parsingSteps = [\n convertToV1FromDataContent,\n convertToV1FromChatCompletionsInput,\n convertToV1FromAnthropicInput,\n ];\n const parsedBlocks = parsingSteps.reduce(\n (blocks, step) => step(blocks),\n blocks\n );\n return parsedBlocks as Array<ContentBlock.Standard>;\n }\n\n toDict(): StoredMessage {\n return {\n type: this.getType(),\n data: (this.toJSON() as SerializedConstructor)\n .kwargs as StoredMessageData,\n };\n }\n\n static lc_name() {\n return \"BaseMessage\";\n }\n\n // Can't be protected for silly reasons\n get _printableFields(): Record<string, unknown> {\n return {\n id: this.id,\n content: this.content,\n name: this.name,\n additional_kwargs: this.additional_kwargs,\n response_metadata: this.response_metadata,\n };\n }\n\n static isInstance(obj: unknown): obj is BaseMessage {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n MESSAGE_SYMBOL in obj &&\n (obj as Record<symbol, unknown>)[MESSAGE_SYMBOL] === true &&\n isMessage(obj)\n );\n }\n\n static [Symbol.hasInstance](obj: unknown) {\n return this.isInstance(obj);\n }\n\n // this private method is used to update the ID for the runtime\n // value as well as in lc_kwargs for serialisation\n _updateId(value: string | undefined) {\n this.id = value;\n\n // lc_attributes wouldn't work here, because jest compares the\n // whole object\n this.lc_kwargs.id = value;\n }\n\n get [Symbol.toStringTag]() {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.constructor as any).lc_name();\n }\n\n // Override the default behavior of console.log\n [Symbol.for(\"nodejs.util.inspect.custom\")](depth: number | null) {\n if (depth === null) {\n return this;\n }\n const printable = stringifyWithDepthLimit(\n this._printableFields,\n Math.max(4, depth)\n );\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return `${(this.constructor as any).lc_name()} ${printable}`;\n }\n\n toFormattedString(format: MessageStringFormat = \"pretty\"): string {\n return convertToFormattedString(this, format);\n }\n}\n\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n\n index?: number;\n};\n\nexport function isOpenAIToolCallArray(\n value?: unknown\n): value is OpenAIToolCall[] {\n return (\n Array.isArray(value) &&\n value.every((v) => typeof (v as OpenAIToolCall).index === \"number\")\n );\n}\n\n/**\n * Default keys that should be preserved (not merged) when concatenating message chunks.\n * These are identification and timestamp fields that shouldn't be summed or concatenated.\n */\nexport const DEFAULT_MERGE_IGNORE_KEYS: readonly string[] = [\n \"index\", // Used for identification in tool calls, not accumulation\n \"created\", // Timestamp field\n \"timestamp\", // Timestamp field\n] as const;\n\n/**\n * Options for controlling merge behavior in `_mergeDicts`.\n */\nexport interface MergeDictsOptions {\n /**\n * Keys to ignore during merging. When a key is in this list:\n * - For numeric values: the original value is preserved (not summed)\n * - For string values: the original value is preserved (not concatenated)\n *\n * Defaults to `DEFAULT_MERGE_IGNORE_KEYS` which includes 'index', 'created', 'timestamp'.\n *\n * @example\n * // Extend defaults with custom keys\n * { ignoreKeys: [...DEFAULT_MERGE_IGNORE_KEYS, 'role', 'customField'] }\n */\n ignoreKeys?: readonly string[];\n}\n\nexport function _mergeDicts(\n /**\n * The left dictionary to merge.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n left: Record<string, any> | undefined,\n /**\n * The right dictionary to merge.\n * @type {Record<string, any>}\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n right: Record<string, any> | undefined,\n /**\n * The options for the merge.\n */\n options?: MergeDictsOptions\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> | undefined {\n /**\n * The keys to ignore during merging.\n */\n const ignoreKeys = options?.ignoreKeys ?? DEFAULT_MERGE_IGNORE_KEYS;\n if (left == null && right == null) {\n return undefined;\n }\n if (left == null || right == null) {\n return left ?? right;\n }\n const merged = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (merged[key] == null) {\n merged[key] = value;\n } else if (value == null) {\n continue;\n } else if (\n typeof merged[key] !== typeof value ||\n Array.isArray(merged[key]) !== Array.isArray(value)\n ) {\n throw new Error(\n `field[${key}] already exists in the message chunk, but with a different type.`\n );\n } else if (typeof merged[key] === \"string\") {\n if (key === \"type\") {\n // Do not merge 'type' fields\n continue;\n } else if (\n [\"id\", \"name\", \"output_version\", \"model_provider\"].includes(key)\n ) {\n // Keep the incoming value for these fields if its defined\n if (value) {\n merged[key] = value;\n }\n } else if (ignoreKeys.includes(key)) {\n // Preserve the original value for ignored keys\n continue;\n } else {\n merged[key] += value;\n }\n } else if (typeof merged[key] === \"number\") {\n if (ignoreKeys.includes(key)) {\n // Preserve the original value for ignored keys\n continue;\n }\n merged[key] = merged[key] + value;\n } else if (typeof merged[key] === \"object\" && !Array.isArray(merged[key])) {\n merged[key] = _mergeDicts(merged[key], value, options);\n } else if (Array.isArray(merged[key])) {\n merged[key] = _mergeLists(merged[key], value, options);\n } else if (merged[key] === value) {\n continue;\n } else {\n console.warn(\n `field[${key}] already exists in this message chunk and value has unsupported type.`\n );\n }\n }\n return merged;\n}\n\nfunction isMergeableIndex(index: unknown): index is number | string {\n return typeof index === \"number\" || typeof index === \"string\";\n}\n\nfunction hasMergeableIndex(\n value: unknown\n): value is { index: number | string } {\n if (typeof value !== \"object\" || value === null) return false;\n if (!(\"index\" in value)) return false;\n return isMergeableIndex(value.index);\n}\n\nfunction hasMergeableId(value: unknown): value is { id: string | number } {\n if (typeof value !== \"object\" || value === null) return false;\n if (!(\"id\" in value)) return false;\n const id = (value as Record<string, unknown>).id;\n return id != null && id !== \"\";\n}\n\nfunction getMergeableTypeBase(type: string): string {\n return type.endsWith(\"_delta\") ? type.slice(0, -\"_delta\".length) : type;\n}\n\nfunction hasMismatchedMergeableType(left: unknown, right: unknown): boolean {\n if (typeof left !== \"object\" || left === null) return false;\n if (typeof right !== \"object\" || right === null) return false;\n if (!(\"type\" in left) || !(\"type\" in right)) return false;\n\n return (\n typeof left.type === \"string\" &&\n typeof right.type === \"string\" &&\n getMergeableTypeBase(left.type) !== getMergeableTypeBase(right.type)\n );\n}\n\n/**\n * Find the index of an existing item in `merged` that should be merged with\n * `item`, based on index and/or id matching.\n *\n * Matching priority:\n * 1. Both have index → match on index (+ id when both present)\n * 2. Neither has index, both have id → match on id alone\n * 3. Otherwise → no match (item should be appended)\n */\nfunction _findMergeTarget<Content extends ContentBlock>(\n merged: Content[],\n item: Content\n): number {\n const itemHasIndex = hasMergeableIndex(item);\n const itemHasId = hasMergeableId(item);\n\n if (!itemHasIndex && !itemHasId) return -1;\n\n return merged.findIndex((leftItem) => {\n const leftHasIndex = hasMergeableIndex(leftItem);\n const leftHasId = hasMergeableId(leftItem);\n\n if (itemHasIndex && leftHasIndex) {\n // Both have index: match on index, with id as tiebreaker\n const indicesMatch = leftItem.index === item.index;\n if (!indicesMatch) return false;\n if (hasMismatchedMergeableType(leftItem, item)) return false;\n if (leftHasId && itemHasId) return leftItem.id === item.id;\n return true; // indices match, one or both missing id\n }\n\n if (!itemHasIndex && !leftHasIndex && itemHasId && leftHasId) {\n // Neither has index: fall back to id-only matching. Handles providers\n // that don't include `index` on streaming tool call deltas.\n return leftItem.id === item.id;\n }\n\n return false;\n });\n}\n\nexport function _mergeLists<Content extends ContentBlock>(\n left?: Content[],\n right?: Content[],\n options?: MergeDictsOptions\n): Content[] | undefined {\n if (left == null && right == null) {\n return undefined;\n } else if (left == null || right == null) {\n return left || right;\n } else {\n const merged = [...left];\n for (const item of right) {\n const toMerge = _findMergeTarget(merged, item);\n if (toMerge !== -1) {\n merged[toMerge] = _mergeDicts(\n merged[toMerge],\n item,\n options\n ) as Content;\n } else if (\n typeof item === \"object\" &&\n item !== null &&\n \"text\" in item &&\n item.text === \"\"\n ) {\n continue;\n } else {\n merged.push(item);\n }\n }\n return merged;\n }\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _mergeObj<T = any>(\n left: T | undefined,\n right: T | undefined,\n options?: MergeDictsOptions\n): T | undefined {\n if (left == null && right == null) {\n return undefined;\n }\n if (left == null || right == null) {\n return left ?? right;\n } else if (typeof left !== typeof right) {\n throw new Error(\n `Cannot merge objects of different types.\\nLeft ${typeof left}\\nRight ${typeof right}`\n );\n } else if (typeof left === \"string\" && typeof right === \"string\") {\n return (left + right) as T;\n } else if (Array.isArray(left) && Array.isArray(right)) {\n return _mergeLists(left, right, options) as T;\n } else if (typeof left === \"object\" && typeof right === \"object\") {\n return _mergeDicts(\n left as Record<string, unknown>,\n right as Record<string, unknown>,\n options\n ) as T;\n } else if (left === right) {\n return left;\n } else {\n throw new Error(\n `Can not merge objects of different types.\\nLeft ${left}\\nRight ${right}`\n );\n }\n}\n\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport abstract class BaseMessageChunk<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n\n static isInstance(obj: unknown): obj is BaseMessageChunk {\n if (!super.isInstance(obj)) {\n return false;\n }\n // Check if obj is an instance of BaseMessageChunk by traversing the prototype chain\n let proto = Object.getPrototypeOf(obj);\n while (proto !== null) {\n if (proto === BaseMessageChunk.prototype) {\n return true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n }\n\n static [Symbol.hasInstance](obj: unknown) {\n return this.isInstance(obj);\n }\n}\n\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\n\nexport function _isMessageFieldWithRole(\n x: BaseMessageLike\n): x is MessageFieldWithRole {\n return typeof (x as MessageFieldWithRole).role === \"string\";\n}\n\nexport type BaseMessageLike =\n | BaseMessage\n | MessageFieldWithRole\n | [MessageType, MessageContent]\n | string\n /**\n * Serialized form of {@link RemoveMessage}. At runtime,\n * {@link coerceMessageLikeToMessage} converts this to a `RemoveMessage`\n * instance which the `add_messages` reducer uses to delete messages by ID.\n */\n | { type: \"remove\"; id: string }\n /**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n } & BaseMessageFields &\n Record<string, unknown>)\n | SerializedConstructor;\n\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport function isBaseMessage(\n messageLike?: unknown\n): messageLike is BaseMessage {\n return typeof (messageLike as BaseMessage)?._getType === \"function\";\n}\n\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport function isBaseMessageChunk(\n messageLike?: unknown\n): messageLike is BaseMessageChunk {\n return BaseMessageChunk.isInstance(messageLike);\n}\n"],"mappings":";;;;;;;;;AAoBA,MAAM,iBAAyB,OAAO,IAAI,mBAAmB;;;;;;AA0E7D,SAAS,gC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AO,YACL,MACA,OACA,OACF;MACK,IAAI,SAAS,OAClB,OAAO;MAEP,MAAM,IAAI,MACR,mDAAmD,KAAK,UAAU,OACpE;AAEJ;;;;;;;;AASA,IAAsB,mBAAtB,MAAsB,yBAGZ,YAA+B;CAGvC,OAAO,WAAW,KAAuC;EACvD,IAAI,CAAC,MAAM,WAAW,GAAG,GACvB,OAAO;EAGT,IAAI,QAAQ,OAAO,eAAe,GAAG;EACrC,OAAO,UAAU,MAAM;GACrB,IAAI,UAAU,iBAAiB,WAC7B,OAAO;GAET,QAAQ,OAAO,eAAe,KAAK;EACrC;EACA,OAAO;CACT;CAEA,QAAQ,OAAO,aAAa,KAAc;EACxC,OAAO,KAAK,WAAW,GAAG;CAC5B;AACF;AAQA,SAAgB,wBACd,GAC2B;CAC3B,OAAO,OAAQ,EAA2B,SAAS;AACrD;;;;AAyBA,SAAgB,cACd,aAC4B;CAC5B,OAAO,OAAQ,aAA6B,aAAa;AAC3D;;;;AAKA,SAAgB,mBACd,aACiC;CACjC,OAAO,iBAAiB,WAAW,WAAW;AAChD"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../src/messages/base.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { isDataContentBlock } from \"./content/data.js\";\nimport { convertToV1FromAnthropicInput } from \"./block_translators/anthropic.js\";\nimport { convertToV1FromDataContent } from \"./block_translators/data.js\";\nimport { convertToV1FromChatCompletionsInput } from \"./block_translators/openai.js\";\nimport {\n $InferMessageContent,\n $InferResponseMetadata,\n MessageStructure,\n MessageType,\n isMessage,\n Message,\n} from \"./message.js\";\nimport {\n convertToFormattedString,\n type MessageStringFormat,\n} from \"./format.js\";\n\n/** @internal */\nconst MESSAGE_SYMBOL: symbol = Symbol.for(\"langchain.message\");\n\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n response_metadata?: Record<string, any>;\n id?: string;\n}\n\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\n\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\n\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\n\nexport type MessageContent = string | Array<ContentBlock>;\n\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n}\n\nexport type BaseMessageFields<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n> = Pick<Message, \"id\" | \"name\"> & {\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\n\n/**\n * Normalize non-string `firstContent` to a block array for merge/spread.\n * Some serializers (e.g. Anthropic-style) yield a single block object instead of a one-element array;\n * spreading that object as an array throws (\"is not iterable\").\n */\nfunction contentBlocksFromNonStringFirst(\n firstContent: MessageContent\n): ContentBlock[] {\n if (Array.isArray(firstContent)) {\n return firstContent;\n }\n if (typeof firstContent === \"string\") {\n return firstContent === \"\" ? [] : [{ type: \"text\", text: firstContent }];\n }\n if (firstContent == null) {\n return [];\n }\n return [firstContent as ContentBlock];\n}\n\nexport function mergeContent(\n firstContent: MessageContent,\n secondContent: MessageContent\n): MessageContent {\n // If first content is a string\n if (typeof firstContent === \"string\") {\n if (firstContent === \"\") {\n return secondContent;\n }\n if (typeof secondContent === \"string\") {\n return firstContent + secondContent;\n } else if (Array.isArray(secondContent) && secondContent.length === 0) {\n return firstContent;\n } else if (\n Array.isArray(secondContent) &&\n secondContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n {\n type: \"text\",\n source_type: \"text\",\n text: firstContent,\n },\n ...secondContent,\n ];\n } else {\n return [{ type: \"text\", text: firstContent }, ...secondContent];\n }\n // If both are arrays\n } else if (Array.isArray(secondContent)) {\n const left = contentBlocksFromNonStringFirst(firstContent);\n return _mergeLists(left, secondContent) ?? [...left, ...secondContent];\n } else {\n if (secondContent === \"\") {\n return firstContent;\n } else if (\n Array.isArray(firstContent) &&\n firstContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n ...firstContent,\n {\n type: \"file\",\n source_type: \"text\",\n text: secondContent,\n },\n ];\n } else {\n const left = contentBlocksFromNonStringFirst(firstContent);\n return [...left, { type: \"text\", text: secondContent }];\n }\n }\n}\n\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport function _mergeStatus(\n left?: \"success\" | \"error\",\n right?: \"success\" | \"error\"\n): \"success\" | \"error\" | undefined {\n if (left === \"error\" || right === \"error\") {\n return \"error\";\n }\n return \"success\";\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringifyWithDepthLimit(obj: any, depthLimit: number): string {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n function helper(obj: any, currentDepth: number): any {\n if (typeof obj !== \"object\" || obj === null || obj === undefined) {\n return obj;\n }\n if (currentDepth >= depthLimit) {\n if (Array.isArray(obj)) {\n return \"[Array]\";\n }\n return \"[Object]\";\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => helper(item, currentDepth + 1));\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = helper(obj[key], currentDepth + 1);\n }\n return result;\n }\n\n return JSON.stringify(helper(obj, 0), null, 2);\n}\n\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport abstract class BaseMessage<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n>\n extends Serializable\n implements Message<TStructure, TRole>\n{\n lc_namespace = [\"langchain_core\", \"messages\"];\n\n lc_serializable = true;\n\n get lc_aliases(): Record<string, string> {\n // exclude snake case conversion to pascal case\n return {\n additional_kwargs: \"additional_kwargs\",\n response_metadata: \"response_metadata\",\n };\n }\n\n readonly [MESSAGE_SYMBOL] = true as const;\n\n abstract readonly type: TRole;\n\n id?: string;\n\n /** @inheritdoc */\n name?: string;\n\n content: $InferMessageContent<TStructure, TRole>;\n\n additional_kwargs: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]\n >;\n\n response_metadata: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"response_metadata\"]\n >;\n\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType {\n return this.type;\n }\n\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType {\n return this._getType();\n }\n\n constructor(\n arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>\n ) {\n const fields: BaseMessageFields<TStructure, TRole> =\n typeof arg === \"string\" || Array.isArray(arg)\n ? ({ content: arg } as BaseMessageFields<TStructure, TRole>)\n : arg;\n if (!fields.additional_kwargs) {\n fields.additional_kwargs = {};\n }\n if (!fields.response_metadata) {\n fields.response_metadata = {};\n }\n super(fields);\n this.name = fields.name;\n if (fields.content === undefined && fields.contentBlocks !== undefined) {\n this.content = fields.contentBlocks as $InferMessageContent<\n TStructure,\n TRole\n >;\n this.response_metadata = {\n output_version: \"v1\",\n ...fields.response_metadata,\n };\n } else if (fields.content !== undefined) {\n this.content = fields.content ?? [];\n this.response_metadata = fields.response_metadata;\n } else {\n this.content = [] as $InferMessageContent<TStructure, TRole>;\n this.response_metadata = fields.response_metadata;\n }\n this.additional_kwargs = fields.additional_kwargs;\n this.id = fields.id;\n }\n\n /** Get text content of the message. */\n get text(): string {\n const textBlocks: ContentBlock.Text[] = this.contentBlocks.filter(\n (block: ContentBlock.Standard) => block.type === \"text\"\n );\n return textBlocks.reduce(\n (acc: string, block: ContentBlock.Text) => acc + (block.text ?? \"\"),\n \"\"\n );\n }\n\n get contentBlocks(): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock> =\n typeof this.content === \"string\"\n ? [{ type: \"text\", text: this.content }]\n : this.content;\n const parsingSteps = [\n convertToV1FromDataContent,\n convertToV1FromChatCompletionsInput,\n convertToV1FromAnthropicInput,\n ];\n const parsedBlocks = parsingSteps.reduce(\n (blocks, step) => step(blocks),\n blocks\n );\n return parsedBlocks as Array<ContentBlock.Standard>;\n }\n\n toDict(): StoredMessage {\n return {\n type: this.getType(),\n data: (this.toJSON() as SerializedConstructor)\n .kwargs as StoredMessageData,\n };\n }\n\n static lc_name() {\n return \"BaseMessage\";\n }\n\n // Can't be protected for silly reasons\n get _printableFields(): Record<string, unknown> {\n return {\n id: this.id,\n content: this.content,\n name: this.name,\n additional_kwargs: this.additional_kwargs,\n response_metadata: this.response_metadata,\n };\n }\n\n static isInstance(obj: unknown): obj is BaseMessage {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n MESSAGE_SYMBOL in obj &&\n (obj as Record<symbol, unknown>)[MESSAGE_SYMBOL] === true &&\n isMessage(obj)\n );\n }\n\n static [Symbol.hasInstance](obj: unknown) {\n return this.isInstance(obj);\n }\n\n // this private method is used to update the ID for the runtime\n // value as well as in lc_kwargs for serialisation\n _updateId(value: string | undefined) {\n this.id = value;\n\n // lc_attributes wouldn't work here, because jest compares the\n // whole object\n this.lc_kwargs.id = value;\n }\n\n get [Symbol.toStringTag]() {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.constructor as any).lc_name();\n }\n\n // Override the default behavior of console.log\n [Symbol.for(\"nodejs.util.inspect.custom\")](depth: number | null) {\n if (depth === null) {\n return this;\n }\n const printable = stringifyWithDepthLimit(\n this._printableFields,\n Math.max(4, depth)\n );\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return `${(this.constructor as any).lc_name()} ${printable}`;\n }\n\n toFormattedString(format: MessageStringFormat = \"pretty\"): string {\n return convertToFormattedString(this, format);\n }\n}\n\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n\n index?: number;\n};\n\nexport function isOpenAIToolCallArray(\n value?: unknown\n): value is OpenAIToolCall[] {\n return (\n Array.isArray(value) &&\n value.every((v) => typeof (v as OpenAIToolCall).index === \"number\")\n );\n}\n\n/**\n * Default keys that should be preserved (not merged) when concatenating message chunks.\n * These are identification and timestamp fields that shouldn't be summed or concatenated.\n */\nexport const DEFAULT_MERGE_IGNORE_KEYS: readonly string[] = [\n \"index\", // Used for identification in tool calls, not accumulation\n \"created\", // Timestamp field\n \"timestamp\", // Timestamp field\n] as const;\n\n/**\n * Options for controlling merge behavior in `_mergeDicts`.\n */\nexport interface MergeDictsOptions {\n /**\n * Keys to ignore during merging. When a key is in this list:\n * - For numeric values: the original value is preserved (not summed)\n * - For string values: the original value is preserved (not concatenated)\n *\n * Defaults to `DEFAULT_MERGE_IGNORE_KEYS` which includes 'index', 'created', 'timestamp'.\n *\n * @example\n * // Extend defaults with custom keys\n * { ignoreKeys: [...DEFAULT_MERGE_IGNORE_KEYS, 'role', 'customField'] }\n */\n ignoreKeys?: readonly string[];\n}\n\nexport function _mergeDicts(\n /**\n * The left dictionary to merge.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n left: Record<string, any> | undefined,\n /**\n * The right dictionary to merge.\n * @type {Record<string, any>}\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n right: Record<string, any> | undefined,\n /**\n * The options for the merge.\n */\n options?: MergeDictsOptions\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> | undefined {\n /**\n * The keys to ignore during merging.\n */\n const ignoreKeys = options?.ignoreKeys ?? DEFAULT_MERGE_IGNORE_KEYS;\n if (left == null && right == null) {\n return undefined;\n }\n if (left == null || right == null) {\n return left ?? right;\n }\n const merged = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (merged[key] == null) {\n merged[key] = value;\n } else if (value == null) {\n continue;\n } else if (\n typeof merged[key] !== typeof value ||\n Array.isArray(merged[key]) !== Array.isArray(value)\n ) {\n throw new Error(\n `field[${key}] already exists in the message chunk, but with a different type.`\n );\n } else if (typeof merged[key] === \"string\") {\n if (key === \"type\") {\n // Do not merge 'type' fields\n continue;\n } else if (\n [\"id\", \"name\", \"output_version\", \"model_provider\"].includes(key)\n ) {\n // Keep the incoming value for these fields if its defined\n if (value) {\n merged[key] = value;\n }\n } else if (ignoreKeys.includes(key)) {\n // Preserve the original value for ignored keys\n continue;\n } else {\n merged[key] += value;\n }\n } else if (typeof merged[key] === \"number\") {\n if (ignoreKeys.includes(key)) {\n // Preserve the original value for ignored keys\n continue;\n }\n merged[key] = merged[key] + value;\n } else if (typeof merged[key] === \"object\" && !Array.isArray(merged[key])) {\n merged[key] = _mergeDicts(merged[key], value, options);\n } else if (Array.isArray(merged[key])) {\n merged[key] = _mergeLists(merged[key], value, options);\n } else if (merged[key] === value) {\n continue;\n } else {\n console.warn(\n `field[${key}] already exists in this message chunk and value has unsupported type.`\n );\n }\n }\n return merged;\n}\n\nfunction isMergeableIndex(index: unknown): index is number | string {\n return typeof index === \"number\" || typeof index === \"string\";\n}\n\nfunction hasMergeableIndex(\n value: unknown\n): value is { index: number | string } {\n if (typeof value !== \"object\" || value === null) return false;\n if (!(\"index\" in value)) return false;\n return isMergeableIndex(value.index);\n}\n\nfunction hasMergeableId(value: unknown): value is { id: string | number } {\n if (typeof value !== \"object\" || value === null) return false;\n if (!(\"id\" in value)) return false;\n const id = (value as Record<string, unknown>).id;\n return id != null && id !== \"\";\n}\n\nfunction getMergeableTypeBase(type: string): string {\n return type.endsWith(\"_delta\") ? type.slice(0, -\"_delta\".length) : type;\n}\n\nfunction hasMismatchedMergeableType(left: unknown, right: unknown): boolean {\n if (typeof left !== \"object\" || left === null) return false;\n if (typeof right !== \"object\" || right === null) return false;\n if (!(\"type\" in left) || !(\"type\" in right)) return false;\n\n return (\n typeof left.type === \"string\" &&\n typeof right.type === \"string\" &&\n getMergeableTypeBase(left.type) !== getMergeableTypeBase(right.type)\n );\n}\n\n/**\n * Find the index of an existing item in `merged` that should be merged with\n * `item`, based on index and/or id matching.\n *\n * Matching priority:\n * 1. Both have index → match on index (+ id when both present)\n * 2. Neither has index, both have id → match on id alone\n * 3. Otherwise → no match (item should be appended)\n */\nfunction _findMergeTarget<Content extends ContentBlock>(\n merged: Content[],\n item: Content\n): number {\n const itemHasIndex = hasMergeableIndex(item);\n const itemHasId = hasMergeableId(item);\n\n if (!itemHasIndex && !itemHasId) return -1;\n\n return merged.findIndex((leftItem) => {\n const leftHasIndex = hasMergeableIndex(leftItem);\n const leftHasId = hasMergeableId(leftItem);\n\n if (itemHasIndex && leftHasIndex) {\n // Both have index: match on index, with id as tiebreaker\n const indicesMatch = leftItem.index === item.index;\n if (!indicesMatch) return false;\n if (hasMismatchedMergeableType(leftItem, item)) return false;\n if (leftHasId && itemHasId) return leftItem.id === item.id;\n return true; // indices match, one or both missing id\n }\n\n if (!itemHasIndex && !leftHasIndex && itemHasId && leftHasId) {\n // Neither has index: fall back to id-only matching. Handles providers\n // that don't include `index` on streaming tool call deltas.\n return leftItem.id === item.id;\n }\n\n return false;\n });\n}\n\nexport function _mergeLists<Content extends ContentBlock>(\n left?: Content[],\n right?: Content[],\n options?: MergeDictsOptions\n): Content[] | undefined {\n if (left == null && right == null) {\n return undefined;\n } else if (left == null || right == null) {\n return left || right;\n } else {\n const merged = [...left];\n for (const item of right) {\n const toMerge = _findMergeTarget(merged, item);\n if (toMerge !== -1) {\n merged[toMerge] = _mergeDicts(\n merged[toMerge],\n item,\n options\n ) as Content;\n } else if (\n typeof item === \"object\" &&\n item !== null &&\n \"text\" in item &&\n item.text === \"\"\n ) {\n continue;\n } else {\n merged.push(item);\n }\n }\n return merged;\n }\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _mergeObj<T = any>(\n left: T | undefined,\n right: T | undefined,\n options?: MergeDictsOptions\n): T | undefined {\n if (left == null && right == null) {\n return undefined;\n }\n if (left == null || right == null) {\n return left ?? right;\n } else if (typeof left !== typeof right) {\n throw new Error(\n `Cannot merge objects of different types.\\nLeft ${typeof left}\\nRight ${typeof right}`\n );\n } else if (typeof left === \"string\" && typeof right === \"string\") {\n return (left + right) as T;\n } else if (Array.isArray(left) && Array.isArray(right)) {\n return _mergeLists(left, right, options) as T;\n } else if (typeof left === \"object\" && typeof right === \"object\") {\n return _mergeDicts(\n left as Record<string, unknown>,\n right as Record<string, unknown>,\n options\n ) as T;\n } else if (left === right) {\n return left;\n } else {\n throw new Error(\n `Can not merge objects of different types.\\nLeft ${left}\\nRight ${right}`\n );\n }\n}\n\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport abstract class BaseMessageChunk<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n\n static isInstance(obj: unknown): obj is BaseMessageChunk {\n if (!super.isInstance(obj)) {\n return false;\n }\n // Check if obj is an instance of BaseMessageChunk by traversing the prototype chain\n let proto = Object.getPrototypeOf(obj);\n while (proto !== null) {\n if (proto === BaseMessageChunk.prototype) {\n return true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n }\n\n static [Symbol.hasInstance](obj: unknown) {\n return this.isInstance(obj);\n }\n}\n\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\n\nexport function _isMessageFieldWithRole(\n x: BaseMessageLike\n): x is MessageFieldWithRole {\n return typeof (x as MessageFieldWithRole).role === \"string\";\n}\n\nexport type BaseMessageLike =\n | BaseMessage\n | MessageFieldWithRole\n | [MessageType, MessageContent]\n | string\n /**\n * Serialized form of {@link RemoveMessage}. At runtime,\n * {@link coerceMessageLikeToMessage} converts this to a `RemoveMessage`\n * instance which the `add_messages` reducer uses to delete messages by ID.\n */\n | { type: \"remove\"; id: string }\n /**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n } & BaseMessageFields &\n Record<string, unknown>)\n | SerializedConstructor;\n\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport function isBaseMessage(\n messageLike?: unknown\n): messageLike is BaseMessage {\n return typeof (messageLike as BaseMessage)?._getType === \"function\";\n}\n\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport function isBaseMessageChunk(\n messageLike?: unknown\n): messageLike is BaseMessageChunk {\n return BaseMessageChunk.isInstance(messageLike);\n}\n"],"mappings":";;;;;;;;;AAoBA,MAAM,iBAAyB,OAAO,IAAI,mBAAmB;;;;;;AA0E7D,SAAS,gCACP,cACgB;CACh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