@langchain/core 0.3.59 → 0.3.60

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 (98) hide show
  1. package/dist/caches/base.cjs +28 -5
  2. package/dist/caches/base.d.ts +13 -1
  3. package/dist/caches/base.js +25 -2
  4. package/dist/callbacks/base.cjs +19 -9
  5. package/dist/callbacks/base.d.ts +37 -22
  6. package/dist/callbacks/dispatch/index.cjs +1 -2
  7. package/dist/callbacks/dispatch/web.cjs +1 -2
  8. package/dist/callbacks/manager.cjs +4 -4
  9. package/dist/callbacks/manager.d.ts +2 -2
  10. package/dist/errors/index.cjs +1 -2
  11. package/dist/example_selectors/conditional.cjs +3 -3
  12. package/dist/indexing/base.cjs +19 -7
  13. package/dist/indexing/base.d.ts +3 -0
  14. package/dist/indexing/base.js +14 -2
  15. package/dist/language_models/base.cjs +2 -2
  16. package/dist/language_models/chat_models.cjs +2 -2
  17. package/dist/load/import_map.cjs +17 -7
  18. package/dist/load/index.cjs +18 -9
  19. package/dist/load/map_keys.cjs +3 -4
  20. package/dist/load/serializable.cjs +2 -2
  21. package/dist/memory.cjs +2 -2
  22. package/dist/messages/ai.cjs +3 -3
  23. package/dist/messages/base.cjs +10 -10
  24. package/dist/messages/chat.cjs +3 -3
  25. package/dist/messages/content_blocks.cjs +9 -10
  26. package/dist/messages/function.cjs +3 -3
  27. package/dist/messages/human.cjs +3 -3
  28. package/dist/messages/system.cjs +3 -3
  29. package/dist/messages/tool.cjs +5 -5
  30. package/dist/messages/transformers.cjs +4 -5
  31. package/dist/messages/utils.cjs +6 -7
  32. package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs +4 -4
  33. package/dist/output_parsers/xml.cjs +2 -2
  34. package/dist/prompts/base.cjs +36 -3
  35. package/dist/runnables/base.cjs +7 -5
  36. package/dist/runnables/base.d.ts +1 -1
  37. package/dist/runnables/base.js +3 -1
  38. package/dist/runnables/config.cjs +6 -6
  39. package/dist/runnables/graph_mermaid.cjs +2 -3
  40. package/dist/runnables/iter.cjs +5 -5
  41. package/dist/runnables/iter.d.ts +1 -1
  42. package/dist/runnables/utils.cjs +2 -2
  43. package/dist/runnables/wrappers.cjs +1 -2
  44. package/dist/runnables/wrappers.d.ts +1 -1
  45. package/dist/singletons/async_local_storage/context.cjs +3 -3
  46. package/dist/singletons/callbacks.cjs +3 -4
  47. package/dist/singletons/callbacks.d.ts +1 -1
  48. package/dist/structured_query/utils.cjs +7 -8
  49. package/dist/tools/index.cjs +2 -2
  50. package/dist/tools/types.cjs +4 -5
  51. package/dist/tools/utils.cjs +3 -3
  52. package/dist/tracers/base.cjs +2 -2
  53. package/dist/tracers/base.d.ts +84 -84
  54. package/dist/tracers/initialize.cjs +2 -3
  55. package/dist/utils/async_caller.cjs +9 -9
  56. package/dist/utils/async_caller.js +9 -9
  57. package/dist/utils/env.cjs +4 -4
  58. package/dist/utils/event_source_parse.cjs +5 -5
  59. package/dist/utils/fast-json-patch/index.cjs +17 -7
  60. package/dist/utils/fast-json-patch/index.d.ts +4 -4
  61. package/dist/utils/fast-json-patch/src/core.cjs +8 -8
  62. package/dist/utils/fast-json-patch/src/duplex.cjs +4 -5
  63. package/dist/utils/fast-json-patch/src/helpers.cjs +10 -10
  64. package/dist/utils/fast-json-patch/src/helpers.d.ts +3 -3
  65. package/dist/utils/function_calling.cjs +3 -3
  66. package/dist/utils/hash.cjs +3 -1
  67. package/dist/utils/hash.d.ts +7 -0
  68. package/dist/utils/hash.js +1 -0
  69. package/dist/utils/js-sha1/hash.cjs +17 -0
  70. package/dist/utils/js-sha1/hash.d.ts +4 -0
  71. package/dist/utils/js-sha1/hash.js +17 -0
  72. package/dist/utils/js-sha256/hash.cjs +448 -0
  73. package/dist/utils/js-sha256/hash.d.ts +1 -0
  74. package/dist/utils/js-sha256/hash.js +445 -0
  75. package/dist/utils/json.cjs +2 -3
  76. package/dist/utils/json_schema.cjs +11 -4
  77. package/dist/utils/json_schema.js +9 -2
  78. package/dist/utils/math.cjs +6 -7
  79. package/dist/utils/ml-distance/distances.cjs +1 -2
  80. package/dist/utils/ml-distance/similarities.cjs +1 -2
  81. package/dist/utils/ml-distance-euclidean/euclidean.cjs +2 -3
  82. package/dist/utils/sax-js/sax.cjs +35 -35
  83. package/dist/utils/sax-js/sax.js +35 -35
  84. package/dist/utils/signal.cjs +1 -2
  85. package/dist/utils/stream.cjs +4 -4
  86. package/dist/utils/tiktoken.cjs +2 -3
  87. package/dist/utils/types/zod.cjs +223 -56
  88. package/dist/utils/types/zod.d.ts +38 -1
  89. package/dist/utils/types/zod.js +202 -39
  90. package/package.json +30 -4
  91. package/utils/hash/insecure.cjs +1 -0
  92. package/utils/hash/insecure.d.cts +1 -0
  93. package/utils/hash/insecure.d.ts +1 -0
  94. package/utils/hash/insecure.js +1 -0
  95. package/utils/hash/sha256.cjs +1 -0
  96. package/utils/hash/sha256.d.cts +1 -0
  97. package/utils/hash/sha256.d.ts +1 -0
  98. package/utils/hash/sha256.js +1 -0
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.InMemoryCache = exports.BaseCache = exports.serializeGeneration = exports.deserializeStoredGeneration = exports.getCacheKey = void 0;
3
+ exports.InMemoryCache = exports.BaseCache = exports.getCacheKey = void 0;
4
+ exports.deserializeStoredGeneration = deserializeStoredGeneration;
5
+ exports.serializeGeneration = serializeGeneration;
4
6
  const hash_js_1 = require("../utils/hash.cjs");
5
7
  const utils_js_1 = require("../messages/utils.cjs");
6
8
  /**
@@ -12,6 +14,9 @@ const utils_js_1 = require("../messages/utils.cjs");
12
14
  * separate concerns and scale horizontally.
13
15
  *
14
16
  * TODO: Make cache key consistent across versions of LangChain.
17
+ *
18
+ * @deprecated Use `makeDefaultKeyEncoder()` to create a custom key encoder.
19
+ * This function will be removed in a future version.
15
20
  */
16
21
  const getCacheKey = (...strings) => (0, hash_js_1.insecureHash)(strings.join("_"));
17
22
  exports.getCacheKey = getCacheKey;
@@ -26,7 +31,6 @@ function deserializeStoredGeneration(storedGeneration) {
26
31
  return { text: storedGeneration.text };
27
32
  }
28
33
  }
29
- exports.deserializeStoredGeneration = deserializeStoredGeneration;
30
34
  function serializeGeneration(generation) {
31
35
  const serializedValue = {
32
36
  text: generation.text,
@@ -36,11 +40,30 @@ function serializeGeneration(generation) {
36
40
  }
37
41
  return serializedValue;
38
42
  }
39
- exports.serializeGeneration = serializeGeneration;
40
43
  /**
41
44
  * Base class for all caches. All caches should extend this class.
42
45
  */
43
46
  class BaseCache {
47
+ constructor() {
48
+ // For backwards compatibility, we use a default key encoder
49
+ // that uses SHA-1 to hash the prompt and LLM key. This will also print a warning
50
+ // about the security implications of using SHA-1 as a cache key.
51
+ Object.defineProperty(this, "keyEncoder", {
52
+ enumerable: true,
53
+ configurable: true,
54
+ writable: true,
55
+ value: exports.getCacheKey
56
+ });
57
+ }
58
+ /**
59
+ * Sets a custom key encoder function for the cache.
60
+ * This function should take a prompt and an LLM key and return a string
61
+ * that will be used as the cache key.
62
+ * @param keyEncoderFn The custom key encoder function.
63
+ */
64
+ makeDefaultKeyEncoder(keyEncoderFn) {
65
+ this.keyEncoder = keyEncoderFn;
66
+ }
44
67
  }
45
68
  exports.BaseCache = BaseCache;
46
69
  const GLOBAL_MAP = new Map();
@@ -66,7 +89,7 @@ class InMemoryCache extends BaseCache {
66
89
  * @returns The data corresponding to the prompt and LLM key, or null if not found.
67
90
  */
68
91
  lookup(prompt, llmKey) {
69
- return Promise.resolve(this.cache.get((0, exports.getCacheKey)(prompt, llmKey)) ?? null);
92
+ return Promise.resolve(this.cache.get(this.keyEncoder(prompt, llmKey)) ?? null);
70
93
  }
71
94
  /**
72
95
  * Updates the cache with new data using a prompt and an LLM key.
@@ -75,7 +98,7 @@ class InMemoryCache extends BaseCache {
75
98
  * @param value The data to be stored.
76
99
  */
77
100
  async update(prompt, llmKey, value) {
78
- this.cache.set((0, exports.getCacheKey)(prompt, llmKey), value);
101
+ this.cache.set(this.keyEncoder(prompt, llmKey), value);
79
102
  }
80
103
  /**
81
104
  * Returns a global instance of InMemoryCache using a predefined global
@@ -1,3 +1,4 @@
1
+ import { type HashKeyEncoder } from "../utils/hash.js";
1
2
  import type { Generation } from "../outputs.js";
2
3
  import { type StoredGeneration } from "../messages/base.js";
3
4
  /**
@@ -9,8 +10,11 @@ import { type StoredGeneration } from "../messages/base.js";
9
10
  * separate concerns and scale horizontally.
10
11
  *
11
12
  * TODO: Make cache key consistent across versions of LangChain.
13
+ *
14
+ * @deprecated Use `makeDefaultKeyEncoder()` to create a custom key encoder.
15
+ * This function will be removed in a future version.
12
16
  */
13
- export declare const getCacheKey: (...strings: string[]) => string;
17
+ export declare const getCacheKey: HashKeyEncoder;
14
18
  export declare function deserializeStoredGeneration(storedGeneration: StoredGeneration): {
15
19
  text: string;
16
20
  message: import("../messages/tool.js").ToolMessage | import("../messages/ai.js").AIMessage | import("../messages/chat.js").ChatMessage | import("../messages/function.js").FunctionMessage | import("../messages/human.js").HumanMessage | import("../messages/system.js").SystemMessage;
@@ -23,6 +27,14 @@ export declare function serializeGeneration(generation: Generation): StoredGener
23
27
  * Base class for all caches. All caches should extend this class.
24
28
  */
25
29
  export declare abstract class BaseCache<T = Generation[]> {
30
+ protected keyEncoder: HashKeyEncoder;
31
+ /**
32
+ * Sets a custom key encoder function for the cache.
33
+ * This function should take a prompt and an LLM key and return a string
34
+ * that will be used as the cache key.
35
+ * @param keyEncoderFn The custom key encoder function.
36
+ */
37
+ makeDefaultKeyEncoder(keyEncoderFn: HashKeyEncoder): void;
26
38
  abstract lookup(prompt: string, llmKey: string): Promise<T | null>;
27
39
  abstract update(prompt: string, llmKey: string, value: T): Promise<void>;
28
40
  }
@@ -9,6 +9,9 @@ import { mapStoredMessageToChatMessage } from "../messages/utils.js";
9
9
  * separate concerns and scale horizontally.
10
10
  *
11
11
  * TODO: Make cache key consistent across versions of LangChain.
12
+ *
13
+ * @deprecated Use `makeDefaultKeyEncoder()` to create a custom key encoder.
14
+ * This function will be removed in a future version.
12
15
  */
13
16
  export const getCacheKey = (...strings) => insecureHash(strings.join("_"));
14
17
  export function deserializeStoredGeneration(storedGeneration) {
@@ -35,6 +38,26 @@ export function serializeGeneration(generation) {
35
38
  * Base class for all caches. All caches should extend this class.
36
39
  */
37
40
  export class BaseCache {
41
+ constructor() {
42
+ // For backwards compatibility, we use a default key encoder
43
+ // that uses SHA-1 to hash the prompt and LLM key. This will also print a warning
44
+ // about the security implications of using SHA-1 as a cache key.
45
+ Object.defineProperty(this, "keyEncoder", {
46
+ enumerable: true,
47
+ configurable: true,
48
+ writable: true,
49
+ value: getCacheKey
50
+ });
51
+ }
52
+ /**
53
+ * Sets a custom key encoder function for the cache.
54
+ * This function should take a prompt and an LLM key and return a string
55
+ * that will be used as the cache key.
56
+ * @param keyEncoderFn The custom key encoder function.
57
+ */
58
+ makeDefaultKeyEncoder(keyEncoderFn) {
59
+ this.keyEncoder = keyEncoderFn;
60
+ }
38
61
  }
39
62
  const GLOBAL_MAP = new Map();
40
63
  /**
@@ -59,7 +82,7 @@ export class InMemoryCache extends BaseCache {
59
82
  * @returns The data corresponding to the prompt and LLM key, or null if not found.
60
83
  */
61
84
  lookup(prompt, llmKey) {
62
- return Promise.resolve(this.cache.get(getCacheKey(prompt, llmKey)) ?? null);
85
+ return Promise.resolve(this.cache.get(this.keyEncoder(prompt, llmKey)) ?? null);
63
86
  }
64
87
  /**
65
88
  * Updates the cache with new data using a prompt and an LLM key.
@@ -68,7 +91,7 @@ export class InMemoryCache extends BaseCache {
68
91
  * @param value The data to be stored.
69
92
  */
70
93
  async update(prompt, llmKey, value) {
71
- this.cache.set(getCacheKey(prompt, llmKey), value);
94
+ this.cache.set(this.keyEncoder(prompt, llmKey), value);
72
95
  }
73
96
  /**
74
97
  * Returns a global instance of InMemoryCache using a predefined global
@@ -15,15 +15,26 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.isBaseCallbackHandler = exports.BaseCallbackHandler = exports.callbackHandlerPrefersStreaming = void 0;
36
+ exports.isBaseCallbackHandler = exports.BaseCallbackHandler = void 0;
37
+ exports.callbackHandlerPrefersStreaming = callbackHandlerPrefersStreaming;
27
38
  const uuid = __importStar(require("uuid"));
28
39
  const serializable_js_1 = require("../load/serializable.cjs");
29
40
  const env_js_1 = require("../utils/env.cjs");
@@ -37,7 +48,6 @@ class BaseCallbackHandlerMethodsClass {
37
48
  function callbackHandlerPrefersStreaming(x) {
38
49
  return "lc_prefer_streaming" in x && x.lc_prefer_streaming;
39
50
  }
40
- exports.callbackHandlerPrefersStreaming = callbackHandlerPrefersStreaming;
41
51
  /**
42
52
  * Abstract base class for creating callback handlers in the LangChain
43
53
  * framework. It provides a set of optional methods that can be overridden
@@ -222,69 +222,84 @@ export declare abstract class BaseCallbackHandler extends BaseCallbackHandlerMet
222
222
  * Called at the start of an LLM or Chat Model run, with the prompt(s)
223
223
  * and the run ID.
224
224
  */
225
- handleLLMStart?(llm: Serialized, prompts: string[], runId: string, parentRunId?: string | undefined, extraParams?: Record<string, unknown> | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runName?: string | undefined): any;
225
+ handleLLMStart?(llm: Serialized, prompts: string[], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>, runName?: string): // eslint-disable-next-line @typescript-eslint/no-explicit-any
226
+ Promise<any> | any;
226
227
  /**
227
228
  * Called when an LLM/ChatModel in `streaming` mode produces a new token
228
229
  */
229
- handleLLMNewToken?(token: string, idx: NewTokenIndices, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, fields?: HandleLLMNewTokenCallbackFields | undefined): any;
230
+ handleLLMNewToken?(token: string, idx: NewTokenIndices, runId: string, parentRunId?: string, tags?: string[], fields?: HandleLLMNewTokenCallbackFields): // eslint-disable-next-line @typescript-eslint/no-explicit-any
231
+ Promise<any> | any;
230
232
  /**
231
233
  * Called if an LLM/ChatModel run encounters an error
232
234
  */
233
- handleLLMError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, extraParams?: Record<string, unknown> | undefined): any;
235
+ handleLLMError?(err: Error, runId: string, parentRunId?: string, tags?: string[], extraParams?: Record<string, unknown>): // eslint-disable-next-line @typescript-eslint/no-explicit-any
236
+ Promise<any> | any;
234
237
  /**
235
238
  * Called at the end of an LLM/ChatModel run, with the output and the run ID.
236
239
  */
237
- handleLLMEnd?(output: LLMResult, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, extraParams?: Record<string, unknown> | undefined): any;
240
+ handleLLMEnd?(output: LLMResult, runId: string, parentRunId?: string, tags?: string[], extraParams?: Record<string, unknown>): // eslint-disable-next-line @typescript-eslint/no-explicit-any
241
+ Promise<any> | any;
238
242
  /**
239
243
  * Called at the start of a Chat Model run, with the prompt(s)
240
244
  * and the run ID.
241
245
  */
242
- handleChatModelStart?(llm: Serialized, messages: BaseMessage[][], runId: string, parentRunId?: string | undefined, extraParams?: Record<string, unknown> | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runName?: string | undefined): any;
246
+ handleChatModelStart?(llm: Serialized, messages: BaseMessage[][], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>, runName?: string): // eslint-disable-next-line @typescript-eslint/no-explicit-any
247
+ Promise<any> | any;
243
248
  /**
244
249
  * Called at the start of a Chain run, with the chain name and inputs
245
250
  * and the run ID.
246
251
  */
247
- handleChainStart?(chain: Serialized, inputs: ChainValues, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runType?: string | undefined, runName?: string | undefined): any;
252
+ handleChainStart?(chain: Serialized, inputs: ChainValues, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>, runType?: string, runName?: string): // eslint-disable-next-line @typescript-eslint/no-explicit-any
253
+ Promise<any> | any;
248
254
  /**
249
255
  * Called if a Chain run encounters an error
250
256
  */
251
- handleChainError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, kwargs?: {
252
- inputs?: Record<string, unknown> | undefined;
253
- } | undefined): any;
257
+ handleChainError?(err: Error, runId: string, parentRunId?: string, tags?: string[], kwargs?: {
258
+ inputs?: Record<string, unknown>;
259
+ }): // eslint-disable-next-line @typescript-eslint/no-explicit-any
260
+ Promise<any> | any;
254
261
  /**
255
262
  * Called at the end of a Chain run, with the outputs and the run ID.
256
263
  */
257
- handleChainEnd?(outputs: ChainValues, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, kwargs?: {
258
- inputs?: Record<string, unknown> | undefined;
259
- } | undefined): any;
264
+ handleChainEnd?(outputs: ChainValues, runId: string, parentRunId?: string, tags?: string[], kwargs?: {
265
+ inputs?: Record<string, unknown>;
266
+ }): // eslint-disable-next-line @typescript-eslint/no-explicit-any
267
+ Promise<any> | any;
260
268
  /**
261
269
  * Called at the start of a Tool run, with the tool name and input
262
270
  * and the run ID.
263
271
  */
264
- handleToolStart?(tool: Serialized, input: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runName?: string | undefined): any;
272
+ handleToolStart?(tool: Serialized, input: string, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>, runName?: string): // eslint-disable-next-line @typescript-eslint/no-explicit-any
273
+ Promise<any> | any;
265
274
  /**
266
275
  * Called if a Tool run encounters an error
267
276
  */
268
- handleToolError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;
277
+ handleToolError?(err: Error, runId: string, parentRunId?: string, tags?: string[]): // eslint-disable-next-line @typescript-eslint/no-explicit-any
278
+ Promise<any> | any;
269
279
  /**
270
280
  * Called at the end of a Tool run, with the tool output and the run ID.
271
281
  */
272
- handleToolEnd?(output: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;
273
- handleText?(text: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): void | Promise<void>;
282
+ handleToolEnd?(output: any, runId: string, parentRunId?: string, tags?: string[]): // eslint-disable-next-line @typescript-eslint/no-explicit-any
283
+ Promise<any> | any;
284
+ handleText?(text: string, runId: string, parentRunId?: string, tags?: string[]): Promise<void> | void;
274
285
  /**
275
286
  * Called when an agent is about to execute an action,
276
287
  * with the action and the run ID.
277
288
  */
278
- handleAgentAction?(action: AgentAction, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): void | Promise<void>;
289
+ handleAgentAction?(action: AgentAction, runId: string, parentRunId?: string, tags?: string[]): Promise<void> | void;
279
290
  /**
280
291
  * Called when an agent finishes execution, before it exits.
281
292
  * with the final output and the run ID.
282
293
  */
283
- handleAgentEnd?(action: AgentFinish, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): void | Promise<void>;
284
- handleRetrieverStart?(retriever: Serialized, query: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, name?: string | undefined): any;
285
- handleRetrieverEnd?(documents: DocumentInterface<Record<string, any>>[], runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;
286
- handleRetrieverError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;
287
- handleCustomEvent?(eventName: string, data: any, runId: string, tags?: string[] | undefined, metadata?: Record<string, any> | undefined): any;
294
+ handleAgentEnd?(action: AgentFinish, runId: string, parentRunId?: string, tags?: string[]): Promise<void> | void;
295
+ handleRetrieverStart?(retriever: Serialized, query: string, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>, name?: string): // eslint-disable-next-line @typescript-eslint/no-explicit-any
296
+ Promise<any> | any;
297
+ handleRetrieverEnd?(documents: DocumentInterface[], runId: string, parentRunId?: string, tags?: string[]): // eslint-disable-next-line @typescript-eslint/no-explicit-any
298
+ Promise<any> | any;
299
+ handleRetrieverError?(err: Error, runId: string, parentRunId?: string, tags?: string[]): // eslint-disable-next-line @typescript-eslint/no-explicit-any
300
+ Promise<any> | any;
301
+ handleCustomEvent?(eventName: string, data: any, runId: string, tags?: string[], metadata?: Record<string, any>): // eslint-disable-next-line @typescript-eslint/no-explicit-any
302
+ Promise<any> | any;
288
303
  };
289
304
  }
290
305
  export declare const isBaseCallbackHandler: (x: unknown) => boolean;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  /* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.dispatchCustomEvent = void 0;
4
+ exports.dispatchCustomEvent = dispatchCustomEvent;
5
5
  const node_async_hooks_1 = require("node:async_hooks");
6
6
  const web_js_1 = require("./web.cjs");
7
7
  const config_js_1 = require("../../runnables/config.cjs");
@@ -46,4 +46,3 @@ payload, config) {
46
46
  const ensuredConfig = (0, config_js_1.ensureConfig)(config);
47
47
  await (0, web_js_1.dispatchCustomEvent)(eventName, payload, ensuredConfig);
48
48
  }
49
- exports.dispatchCustomEvent = dispatchCustomEvent;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.dispatchCustomEvent = void 0;
3
+ exports.dispatchCustomEvent = dispatchCustomEvent;
4
4
  const config_js_1 = require("../../runnables/config.cjs");
5
5
  /**
6
6
  * Dispatch a custom event. Requires an explicit config object.
@@ -56,4 +56,3 @@ payload, config) {
56
56
  await callbackManager.handleCustomEvent?.(name, payload, parentRunId);
57
57
  }
58
58
  }
59
- exports.dispatchCustomEvent = dispatchCustomEvent;
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.traceAsGroup = exports.TraceGroup = exports.ensureHandler = exports.CallbackManager = exports.CallbackManagerForToolRun = exports.CallbackManagerForChainRun = exports.CallbackManagerForLLMRun = exports.CallbackManagerForRetrieverRun = exports.BaseRunManager = exports.BaseCallbackManager = exports.parseCallbackConfigArg = void 0;
3
+ exports.TraceGroup = exports.CallbackManager = exports.CallbackManagerForToolRun = exports.CallbackManagerForChainRun = exports.CallbackManagerForLLMRun = exports.CallbackManagerForRetrieverRun = exports.BaseRunManager = exports.BaseCallbackManager = void 0;
4
+ exports.parseCallbackConfigArg = parseCallbackConfigArg;
5
+ exports.ensureHandler = ensureHandler;
6
+ exports.traceAsGroup = traceAsGroup;
4
7
  const uuid_1 = require("uuid");
5
8
  const base_js_1 = require("./base.cjs");
6
9
  const console_js_1 = require("../tracers/console.cjs");
@@ -22,7 +25,6 @@ function parseCallbackConfigArg(arg) {
22
25
  return arg;
23
26
  }
24
27
  }
25
- exports.parseCallbackConfigArg = parseCallbackConfigArg;
26
28
  /**
27
29
  * Manage callbacks from different components of LangChain.
28
30
  */
@@ -808,7 +810,6 @@ function ensureHandler(handler) {
808
810
  }
809
811
  return base_js_1.BaseCallbackHandler.fromMethods(handler);
810
812
  }
811
- exports.ensureHandler = ensureHandler;
812
813
  /**
813
814
  * @deprecated Use [`traceable`](https://docs.smith.langchain.com/observability/how_to_guides/tracing/annotate_code)
814
815
  * from "langsmith" instead.
@@ -887,4 +888,3 @@ async function traceAsGroup(groupOptions, enclosedCode, ...args) {
887
888
  throw err;
888
889
  }
889
890
  }
890
- exports.traceAsGroup = traceAsGroup;
@@ -165,8 +165,8 @@ export declare class TraceGroup {
165
165
  private options?;
166
166
  private runManager?;
167
167
  constructor(groupName: string, options?: {
168
- projectName?: string | undefined;
169
- exampleId?: string | undefined;
168
+ projectName?: string;
169
+ exampleId?: string;
170
170
  } | undefined);
171
171
  private getTraceGroupCallbackManager;
172
172
  start(inputs?: ChainValues): Promise<CallbackManager>;
@@ -2,10 +2,9 @@
2
2
  /* eslint-disable @typescript-eslint/no-explicit-any */
3
3
  /* eslint-disable no-param-reassign */
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.addLangChainErrorFields = void 0;
5
+ exports.addLangChainErrorFields = addLangChainErrorFields;
6
6
  function addLangChainErrorFields(error, lc_error_code) {
7
7
  error.lc_error_code = lc_error_code;
8
8
  error.message = `${error.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/\n`;
9
9
  return error;
10
10
  }
11
- exports.addLangChainErrorFields = addLangChainErrorFields;
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isChatModel = exports.isLLM = exports.ConditionalPromptSelector = exports.BasePromptSelector = void 0;
3
+ exports.ConditionalPromptSelector = exports.BasePromptSelector = void 0;
4
+ exports.isLLM = isLLM;
5
+ exports.isChatModel = isChatModel;
4
6
  /**
5
7
  * Abstract class that defines the interface for selecting a prompt for a
6
8
  * given language model.
@@ -65,7 +67,6 @@ exports.ConditionalPromptSelector = ConditionalPromptSelector;
65
67
  function isLLM(llm) {
66
68
  return llm._modelType() === "base_llm";
67
69
  }
68
- exports.isLLM = isLLM;
69
70
  /**
70
71
  * Type guard function that checks if a given language model is of type
71
72
  * `BaseChatModel`.
@@ -73,4 +74,3 @@ exports.isLLM = isLLM;
73
74
  function isChatModel(llm) {
74
75
  return llm._modelType() === "base_chat_model";
75
76
  }
76
- exports.isChatModel = isChatModel;
@@ -1,6 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.index = exports._isBaseDocumentLoader = exports._getSourceIdAssigner = exports._deduplicateInOrder = exports._batch = exports._HashedDocument = void 0;
3
+ exports._isBaseDocumentLoader = exports._HashedDocument = void 0;
4
+ exports._batch = _batch;
5
+ exports._deduplicateInOrder = _deduplicateInOrder;
6
+ exports._getSourceIdAssigner = _getSourceIdAssigner;
7
+ exports.index = index;
4
8
  const uuid_1 = require("uuid");
5
9
  const record_manager_js_1 = require("./record_manager.cjs");
6
10
  const hash_js_1 = require("../utils/hash.cjs");
@@ -48,10 +52,22 @@ class _HashedDocument {
48
52
  writable: true,
49
53
  value: void 0
50
54
  });
55
+ // For backwards compatibility, we use a default key encoder
56
+ // that uses SHA-1 to hash the prompt and LLM key. This will also print a warning
57
+ // about the security implications of using SHA-1 as a key encoder.
58
+ Object.defineProperty(this, "keyEncoder", {
59
+ enumerable: true,
60
+ configurable: true,
61
+ writable: true,
62
+ value: hash_js_1.insecureHash
63
+ });
51
64
  this.uid = fields.uid;
52
65
  this.pageContent = fields.pageContent;
53
66
  this.metadata = fields.metadata;
54
67
  }
68
+ makeDefaultKeyEncoder(keyEncoderFn) {
69
+ this.keyEncoder = keyEncoderFn;
70
+ }
55
71
  calculateHashes() {
56
72
  const forbiddenKeys = ["hash_", "content_hash", "metadata_hash"];
57
73
  for (const key of forbiddenKeys) {
@@ -89,12 +105,12 @@ class _HashedDocument {
89
105
  return doc;
90
106
  }
91
107
  _hashStringToUUID(inputString) {
92
- const hash_value = (0, hash_js_1.insecureHash)(inputString);
108
+ const hash_value = this.keyEncoder(inputString);
93
109
  return (0, uuid_1.v5)(hash_value, record_manager_js_1.UUIDV5_NAMESPACE);
94
110
  }
95
111
  _hashNestedDictToUUID(data) {
96
112
  const serialized_data = JSON.stringify(data, Object.keys(data).sort());
97
- const hash_value = (0, hash_js_1.insecureHash)(serialized_data);
113
+ const hash_value = this.keyEncoder(serialized_data);
98
114
  return (0, uuid_1.v5)(hash_value, record_manager_js_1.UUIDV5_NAMESPACE);
99
115
  }
100
116
  }
@@ -114,7 +130,6 @@ function _batch(size, iterable) {
114
130
  }
115
131
  return batches;
116
132
  }
117
- exports._batch = _batch;
118
133
  function _deduplicateInOrder(hashedDocuments) {
119
134
  const seen = new Set();
120
135
  const deduplicated = [];
@@ -129,7 +144,6 @@ function _deduplicateInOrder(hashedDocuments) {
129
144
  }
130
145
  return deduplicated;
131
146
  }
132
- exports._deduplicateInOrder = _deduplicateInOrder;
133
147
  function _getSourceIdAssigner(sourceIdKey) {
134
148
  if (sourceIdKey === null) {
135
149
  return (_doc) => null;
@@ -144,7 +158,6 @@ function _getSourceIdAssigner(sourceIdKey) {
144
158
  throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof sourceIdKey}`);
145
159
  }
146
160
  }
147
- exports._getSourceIdAssigner = _getSourceIdAssigner;
148
161
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
149
162
  const _isBaseDocumentLoader = (arg) => {
150
163
  if ("load" in arg &&
@@ -269,4 +282,3 @@ async function index(args) {
269
282
  numSkipped,
270
283
  };
271
284
  }
272
- exports.index = index;
@@ -1,5 +1,6 @@
1
1
  import { VectorStore } from "../vectorstores.js";
2
2
  import { RecordManagerInterface } from "./record_manager.js";
3
+ import { type HashKeyEncoder } from "../utils/hash.js";
3
4
  import { DocumentInterface } from "../documents/document.js";
4
5
  import { BaseDocumentLoader } from "../document_loaders/base.js";
5
6
  type Metadata = Record<string, unknown>;
@@ -37,7 +38,9 @@ export declare class _HashedDocument implements HashedDocumentInterface {
37
38
  metadataHash?: string;
38
39
  pageContent: string;
39
40
  metadata: Metadata;
41
+ private keyEncoder;
40
42
  constructor(fields: HashedDocumentArgs);
43
+ makeDefaultKeyEncoder(keyEncoderFn: HashKeyEncoder): void;
41
44
  calculateHashes(): void;
42
45
  toDocument(): DocumentInterface;
43
46
  static fromDocument(document: DocumentInterface, uid?: string): _HashedDocument;
@@ -45,10 +45,22 @@ export class _HashedDocument {
45
45
  writable: true,
46
46
  value: void 0
47
47
  });
48
+ // For backwards compatibility, we use a default key encoder
49
+ // that uses SHA-1 to hash the prompt and LLM key. This will also print a warning
50
+ // about the security implications of using SHA-1 as a key encoder.
51
+ Object.defineProperty(this, "keyEncoder", {
52
+ enumerable: true,
53
+ configurable: true,
54
+ writable: true,
55
+ value: insecureHash
56
+ });
48
57
  this.uid = fields.uid;
49
58
  this.pageContent = fields.pageContent;
50
59
  this.metadata = fields.metadata;
51
60
  }
61
+ makeDefaultKeyEncoder(keyEncoderFn) {
62
+ this.keyEncoder = keyEncoderFn;
63
+ }
52
64
  calculateHashes() {
53
65
  const forbiddenKeys = ["hash_", "content_hash", "metadata_hash"];
54
66
  for (const key of forbiddenKeys) {
@@ -86,12 +98,12 @@ export class _HashedDocument {
86
98
  return doc;
87
99
  }
88
100
  _hashStringToUUID(inputString) {
89
- const hash_value = insecureHash(inputString);
101
+ const hash_value = this.keyEncoder(inputString);
90
102
  return uuidv5(hash_value, UUIDV5_NAMESPACE);
91
103
  }
92
104
  _hashNestedDictToUUID(data) {
93
105
  const serialized_data = JSON.stringify(data, Object.keys(data).sort());
94
- const hash_value = insecureHash(serialized_data);
106
+ const hash_value = this.keyEncoder(serialized_data);
95
107
  return uuidv5(hash_value, UUIDV5_NAMESPACE);
96
108
  }
97
109
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BaseLanguageModel = exports.BaseLangChain = exports.calculateMaxTokens = exports.isOpenAITool = exports.getModelContextSize = exports.getEmbeddingContextSize = exports.getModelNameForTiktoken = void 0;
3
+ exports.BaseLanguageModel = exports.BaseLangChain = exports.calculateMaxTokens = exports.getModelContextSize = exports.getEmbeddingContextSize = exports.getModelNameForTiktoken = void 0;
4
+ exports.isOpenAITool = isOpenAITool;
4
5
  const base_js_1 = require("../caches/base.cjs");
5
6
  const prompt_values_js_1 = require("../prompt_values.cjs");
6
7
  const utils_js_1 = require("../messages/utils.cjs");
@@ -82,7 +83,6 @@ function isOpenAITool(tool) {
82
83
  }
83
84
  return false;
84
85
  }
85
- exports.isOpenAITool = isOpenAITool;
86
86
  const calculateMaxTokens = async ({ prompt, modelName, }) => {
87
87
  let numTokens;
88
88
  try {
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SimpleChatModel = exports.BaseChatModel = exports.createChatMessageChunkEncoderStream = void 0;
3
+ exports.SimpleChatModel = exports.BaseChatModel = void 0;
4
+ exports.createChatMessageChunkEncoderStream = createChatMessageChunkEncoderStream;
4
5
  const index_js_1 = require("../messages/index.cjs");
5
6
  const outputs_js_1 = require("../outputs.cjs");
6
7
  const base_js_1 = require("./base.cjs");
@@ -26,7 +27,6 @@ function createChatMessageChunkEncoderStream() {
26
27
  },
27
28
  });
28
29
  }
29
- exports.createChatMessageChunkEncoderStream = createChatMessageChunkEncoderStream;
30
30
  function _formatForTracing(messages) {
31
31
  const messagesToTrace = [];
32
32
  for (const message of messages) {
@@ -16,13 +16,23 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
16
16
  }) : function(o, v) {
17
17
  o["default"] = v;
18
18
  });
19
- var __importStar = (this && this.__importStar) || function (mod) {
20
- if (mod && mod.__esModule) return mod;
21
- var result = {};
22
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
- __setModuleDefault(result, mod);
24
- return result;
25
- };
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
26
36
  Object.defineProperty(exports, "__esModule", { value: true });
27
37
  exports.vectorstores = exports.utils__types = exports.utils__tiktoken = exports.utils__testing = exports.utils__stream = exports.utils__math = exports.utils__json_schema = exports.utils__json_patch = exports.utils__hash = exports.utils__function_calling = exports.utils__env = exports.utils__chunk_array = exports.utils__async_caller = exports.tracers__tracer_langchain_v1 = exports.tracers__tracer_langchain = exports.tracers__run_collector = exports.tracers__log_stream = exports.tracers__initialize = exports.tracers__console = exports.tracers__base = exports.tools = exports.stores = exports.retrievers = exports.runnables = exports.prompt_values = exports.prompts = exports.outputs = exports.output_parsers = exports.messages = exports.memory = exports.load__serializable = exports.language_models__llms = exports.language_models__chat_models = exports.language_models__base = exports.example_selectors = exports.embeddings = exports.documents = exports.chat_history = exports.callbacks__promises = exports.callbacks__manager = exports.callbacks__base = exports.caches = exports.agents = void 0;
28
38
  exports.agents = __importStar(require("../agents.cjs"));