@langchain/core 0.2.15 → 0.2.17

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 (103) hide show
  1. package/caches.cjs +1 -1
  2. package/caches.d.cts +1 -1
  3. package/caches.d.ts +1 -1
  4. package/caches.js +1 -1
  5. package/callbacks/dispatch/web.cjs +1 -0
  6. package/callbacks/dispatch/web.d.cts +1 -0
  7. package/callbacks/dispatch/web.d.ts +1 -0
  8. package/callbacks/dispatch/web.js +1 -0
  9. package/callbacks/dispatch.cjs +1 -0
  10. package/callbacks/dispatch.d.cts +1 -0
  11. package/callbacks/dispatch.d.ts +1 -0
  12. package/callbacks/dispatch.js +1 -0
  13. package/dist/{caches.cjs → caches/base.cjs} +6 -6
  14. package/dist/{caches.d.ts → caches/base.d.ts} +7 -7
  15. package/dist/{caches.js → caches/base.js} +6 -6
  16. package/dist/caches/tests/in_memory_cache.test.d.ts +1 -0
  17. package/dist/caches/tests/in_memory_cache.test.js +33 -0
  18. package/dist/callbacks/base.cjs +8 -0
  19. package/dist/callbacks/base.d.ts +16 -10
  20. package/dist/callbacks/base.js +8 -0
  21. package/dist/callbacks/dispatch/index.cjs +49 -0
  22. package/dist/callbacks/dispatch/index.d.ts +35 -0
  23. package/dist/callbacks/dispatch/index.js +45 -0
  24. package/dist/callbacks/dispatch/web.cjs +61 -0
  25. package/dist/callbacks/dispatch/web.d.ts +32 -0
  26. package/dist/callbacks/dispatch/web.js +57 -0
  27. package/dist/callbacks/manager.cjs +20 -0
  28. package/dist/callbacks/manager.d.ts +2 -1
  29. package/dist/callbacks/manager.js +20 -0
  30. package/dist/language_models/base.cjs +4 -4
  31. package/dist/language_models/base.d.ts +2 -2
  32. package/dist/language_models/base.js +1 -1
  33. package/dist/language_models/chat_models.d.ts +22 -5
  34. package/dist/language_models/llms.d.ts +1 -1
  35. package/dist/language_models/tests/chat_models.test.js +33 -0
  36. package/dist/load/import_map.cjs +2 -2
  37. package/dist/load/import_map.d.ts +2 -2
  38. package/dist/load/import_map.js +2 -2
  39. package/dist/messages/ai.cjs +19 -0
  40. package/dist/messages/ai.d.ts +2 -0
  41. package/dist/messages/ai.js +19 -0
  42. package/dist/messages/base.cjs +95 -5
  43. package/dist/messages/base.d.ts +5 -1
  44. package/dist/messages/base.js +93 -4
  45. package/dist/messages/chat.cjs +12 -0
  46. package/dist/messages/chat.d.ts +2 -0
  47. package/dist/messages/chat.js +12 -0
  48. package/dist/messages/index.cjs +1 -0
  49. package/dist/messages/index.d.ts +2 -1
  50. package/dist/messages/index.js +1 -0
  51. package/dist/messages/modifier.cjs +35 -0
  52. package/dist/messages/modifier.d.ts +19 -0
  53. package/dist/messages/modifier.js +31 -0
  54. package/dist/messages/tests/base_message.test.js +134 -2
  55. package/dist/messages/tests/message_utils.test.js +54 -2
  56. package/dist/messages/tool.cjs +45 -0
  57. package/dist/messages/tool.d.ts +29 -0
  58. package/dist/messages/tool.js +46 -1
  59. package/dist/messages/transformers.cjs +6 -0
  60. package/dist/messages/transformers.d.ts +3 -2
  61. package/dist/messages/transformers.js +6 -0
  62. package/dist/messages/utils.cjs +5 -1
  63. package/dist/messages/utils.js +5 -1
  64. package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs +2 -0
  65. package/dist/output_parsers/openai_tools/json_output_tools_parsers.js +2 -0
  66. package/dist/runnables/base.cjs +104 -1
  67. package/dist/runnables/base.d.ts +50 -0
  68. package/dist/runnables/base.js +101 -0
  69. package/dist/runnables/index.cjs +2 -1
  70. package/dist/runnables/index.d.ts +1 -1
  71. package/dist/runnables/index.js +1 -1
  72. package/dist/runnables/tests/runnable_stream_events.test.js +1 -1
  73. package/dist/runnables/tests/runnable_stream_events_v2.test.js +106 -1
  74. package/dist/runnables/tests/runnable_tools.test.d.ts +1 -0
  75. package/dist/runnables/tests/runnable_tools.test.js +149 -0
  76. package/dist/{tools.cjs → tools/index.cjs} +135 -47
  77. package/dist/{tools.d.ts → tools/index.d.ts} +76 -47
  78. package/dist/{tools.js → tools/index.js} +134 -45
  79. package/dist/tools/tests/tools.test.d.ts +1 -0
  80. package/dist/tools/tests/tools.test.js +85 -0
  81. package/dist/tools/utils.cjs +28 -0
  82. package/dist/tools/utils.d.ts +11 -0
  83. package/dist/tools/utils.js +23 -0
  84. package/dist/tracers/base.cjs +1 -0
  85. package/dist/tracers/base.d.ts +1 -1
  86. package/dist/tracers/base.js +1 -0
  87. package/dist/tracers/event_stream.cjs +15 -0
  88. package/dist/tracers/event_stream.d.ts +1 -0
  89. package/dist/tracers/event_stream.js +15 -0
  90. package/dist/types/zod.cjs +2 -0
  91. package/dist/types/zod.d.ts +2 -0
  92. package/dist/types/zod.js +1 -0
  93. package/dist/utils/function_calling.cjs +38 -10
  94. package/dist/utils/function_calling.d.ts +32 -11
  95. package/dist/utils/function_calling.js +36 -9
  96. package/dist/utils/testing/index.cjs +10 -3
  97. package/dist/utils/testing/index.d.ts +1 -1
  98. package/dist/utils/testing/index.js +9 -2
  99. package/package.json +28 -1
  100. package/tools.cjs +1 -1
  101. package/tools.d.cts +1 -1
  102. package/tools.d.ts +1 -1
  103. package/tools.js +1 -1
package/caches.cjs CHANGED
@@ -1 +1 @@
1
- module.exports = require('./dist/caches.cjs');
1
+ module.exports = require('./dist/caches/base.cjs');
package/caches.d.cts CHANGED
@@ -1 +1 @@
1
- export * from './dist/caches.js'
1
+ export * from './dist/caches/base.js'
package/caches.d.ts CHANGED
@@ -1 +1 @@
1
- export * from './dist/caches.js'
1
+ export * from './dist/caches/base.js'
package/caches.js CHANGED
@@ -1 +1 @@
1
- export * from './dist/caches.js'
1
+ export * from './dist/caches/base.js'
@@ -0,0 +1 @@
1
+ module.exports = require('../../dist/callbacks/dispatch/web.cjs');
@@ -0,0 +1 @@
1
+ export * from '../../dist/callbacks/dispatch/web.js'
@@ -0,0 +1 @@
1
+ export * from '../../dist/callbacks/dispatch/web.js'
@@ -0,0 +1 @@
1
+ export * from '../../dist/callbacks/dispatch/web.js'
@@ -0,0 +1 @@
1
+ module.exports = require('../dist/callbacks/dispatch/index.cjs');
@@ -0,0 +1 @@
1
+ export * from '../dist/callbacks/dispatch/index.js'
@@ -0,0 +1 @@
1
+ export * from '../dist/callbacks/dispatch/index.js'
@@ -0,0 +1 @@
1
+ export * from '../dist/callbacks/dispatch/index.js'
@@ -1,17 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.InMemoryCache = exports.BaseCache = exports.serializeGeneration = exports.deserializeStoredGeneration = exports.getCacheKey = void 0;
4
- const hash_js_1 = require("./utils/hash.cjs");
5
- const utils_js_1 = require("./messages/utils.cjs");
4
+ const hash_js_1 = require("../utils/hash.cjs");
5
+ const utils_js_1 = require("../messages/utils.cjs");
6
6
  /**
7
- * This cache key should be consistent across all versions of langchain.
8
- * It is currently NOT consistent across versions of langchain.
7
+ * This cache key should be consistent across all versions of LangChain.
8
+ * It is currently NOT consistent across versions of LangChain.
9
9
  *
10
10
  * A huge benefit of having a remote cache (like redis) is that you can
11
11
  * access the cache from different processes/machines. The allows you to
12
- * seperate concerns and scale horizontally.
12
+ * separate concerns and scale horizontally.
13
13
  *
14
- * TODO: Make cache key consistent across versions of langchain.
14
+ * TODO: Make cache key consistent across versions of LangChain.
15
15
  */
16
16
  const getCacheKey = (...strings) => (0, hash_js_1.insecureHash)(strings.join("_"));
17
17
  exports.getCacheKey = getCacheKey;
@@ -1,19 +1,19 @@
1
- import type { Generation } from "./outputs.js";
2
- import { type StoredGeneration } from "./messages/base.js";
1
+ import type { Generation } from "../outputs.js";
2
+ import { type StoredGeneration } from "../messages/base.js";
3
3
  /**
4
- * This cache key should be consistent across all versions of langchain.
5
- * It is currently NOT consistent across versions of langchain.
4
+ * This cache key should be consistent across all versions of LangChain.
5
+ * It is currently NOT consistent across versions of LangChain.
6
6
  *
7
7
  * A huge benefit of having a remote cache (like redis) is that you can
8
8
  * access the cache from different processes/machines. The allows you to
9
- * seperate concerns and scale horizontally.
9
+ * separate concerns and scale horizontally.
10
10
  *
11
- * TODO: Make cache key consistent across versions of langchain.
11
+ * TODO: Make cache key consistent across versions of LangChain.
12
12
  */
13
13
  export declare const getCacheKey: (...strings: string[]) => string;
14
14
  export declare function deserializeStoredGeneration(storedGeneration: StoredGeneration): {
15
15
  text: string;
16
- 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;
16
+ 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;
17
17
  } | {
18
18
  text: string;
19
19
  message?: undefined;
@@ -1,14 +1,14 @@
1
- import { insecureHash } from "./utils/hash.js";
2
- import { mapStoredMessageToChatMessage } from "./messages/utils.js";
1
+ import { insecureHash } from "../utils/hash.js";
2
+ import { mapStoredMessageToChatMessage } from "../messages/utils.js";
3
3
  /**
4
- * This cache key should be consistent across all versions of langchain.
5
- * It is currently NOT consistent across versions of langchain.
4
+ * This cache key should be consistent across all versions of LangChain.
5
+ * It is currently NOT consistent across versions of LangChain.
6
6
  *
7
7
  * A huge benefit of having a remote cache (like redis) is that you can
8
8
  * access the cache from different processes/machines. The allows you to
9
- * seperate concerns and scale horizontally.
9
+ * separate concerns and scale horizontally.
10
10
  *
11
- * TODO: Make cache key consistent across versions of langchain.
11
+ * TODO: Make cache key consistent across versions of LangChain.
12
12
  */
13
13
  export const getCacheKey = (...strings) => insecureHash(strings.join("_"));
14
14
  export function deserializeStoredGeneration(storedGeneration) {
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,33 @@
1
+ import { InMemoryCache } from "../base.js";
2
+ test("InMemoryCache works", async () => {
3
+ const cache = new InMemoryCache();
4
+ await cache.update("prompt", "key1", [
5
+ {
6
+ text: "text1",
7
+ },
8
+ ]);
9
+ const result = await cache.lookup("prompt", "key1");
10
+ expect(result).toBeDefined();
11
+ if (!result) {
12
+ return;
13
+ }
14
+ expect(result[0].text).toBe("text1");
15
+ });
16
+ test("InMemoryCache works with complex message types", async () => {
17
+ const cache = new InMemoryCache();
18
+ await cache.update("prompt", "key1", [
19
+ {
20
+ type: "text",
21
+ text: "text1",
22
+ },
23
+ ]);
24
+ const result = await cache.lookup("prompt", "key1");
25
+ expect(result).toBeDefined();
26
+ if (!result) {
27
+ return;
28
+ }
29
+ expect(result[0]).toEqual({
30
+ type: "text",
31
+ text: "text1",
32
+ });
33
+ });
@@ -109,6 +109,12 @@ class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass {
109
109
  writable: true,
110
110
  value: false
111
111
  });
112
+ Object.defineProperty(this, "ignoreCustomEvent", {
113
+ enumerable: true,
114
+ configurable: true,
115
+ writable: true,
116
+ value: false
117
+ });
112
118
  Object.defineProperty(this, "raiseError", {
113
119
  enumerable: true,
114
120
  configurable: true,
@@ -127,6 +133,8 @@ class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass {
127
133
  this.ignoreChain = input.ignoreChain ?? this.ignoreChain;
128
134
  this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent;
129
135
  this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever;
136
+ this.ignoreCustomEvent =
137
+ input.ignoreCustomEvent ?? this.ignoreCustomEvent;
130
138
  this.raiseError = input.raiseError ?? this.raiseError;
131
139
  this.awaitHandlers =
132
140
  this.raiseError || (input._awaitHandler ?? this.awaitHandlers);
@@ -16,6 +16,7 @@ export interface BaseCallbackHandlerInput {
16
16
  ignoreChain?: boolean;
17
17
  ignoreAgent?: boolean;
18
18
  ignoreRetriever?: boolean;
19
+ ignoreCustomEvent?: boolean;
19
20
  _awaitHandler?: boolean;
20
21
  raiseError?: boolean;
21
22
  }
@@ -40,7 +41,7 @@ declare abstract class BaseCallbackHandlerMethodsClass {
40
41
  * Called at the start of an LLM or Chat Model run, with the prompt(s)
41
42
  * and the run ID.
42
43
  */
43
- handleLLMStart?(llm: Serialized, prompts: string[], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>, name?: string): // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
+ 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
44
45
  Promise<any> | any;
45
46
  /**
46
47
  * Called when an LLM/ChatModel in `streaming` mode produces a new token
@@ -68,13 +69,13 @@ declare abstract class BaseCallbackHandlerMethodsClass {
68
69
  * Called at the start of a Chat Model run, with the prompt(s)
69
70
  * and the run ID.
70
71
  */
71
- handleChatModelStart?(llm: Serialized, messages: BaseMessage[][], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>, name?: string): // eslint-disable-next-line @typescript-eslint/no-explicit-any
72
+ 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
72
73
  Promise<any> | any;
73
74
  /**
74
75
  * Called at the start of a Chain run, with the chain name and inputs
75
76
  * and the run ID.
76
77
  */
77
- handleChainStart?(chain: Serialized, inputs: ChainValues, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>, runType?: string, name?: string): // eslint-disable-next-line @typescript-eslint/no-explicit-any
78
+ 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
78
79
  Promise<any> | any;
79
80
  /**
80
81
  * Called if a Chain run encounters an error
@@ -94,7 +95,7 @@ declare abstract class BaseCallbackHandlerMethodsClass {
94
95
  * Called at the start of a Tool run, with the tool name and input
95
96
  * and the run ID.
96
97
  */
97
- handleToolStart?(tool: Serialized, input: string, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>, name?: string): // eslint-disable-next-line @typescript-eslint/no-explicit-any
98
+ 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
98
99
  Promise<any> | any;
99
100
  /**
100
101
  * Called if a Tool run encounters an error
@@ -104,7 +105,7 @@ declare abstract class BaseCallbackHandlerMethodsClass {
104
105
  /**
105
106
  * Called at the end of a Tool run, with the tool output and the run ID.
106
107
  */
107
- handleToolEnd?(output: string, runId: string, parentRunId?: string, tags?: string[]): // eslint-disable-next-line @typescript-eslint/no-explicit-any
108
+ handleToolEnd?(output: any, runId: string, parentRunId?: string, tags?: string[]): // eslint-disable-next-line @typescript-eslint/no-explicit-any
108
109
  Promise<any> | any;
109
110
  handleText?(text: string, runId: string, parentRunId?: string, tags?: string[]): Promise<void> | void;
110
111
  /**
@@ -123,6 +124,8 @@ declare abstract class BaseCallbackHandlerMethodsClass {
123
124
  Promise<any> | any;
124
125
  handleRetrieverError?(err: Error, runId: string, parentRunId?: string, tags?: string[]): // eslint-disable-next-line @typescript-eslint/no-explicit-any
125
126
  Promise<any> | any;
127
+ handleCustomEvent?(eventName: string, data: any, runId: string, tags?: string[], metadata?: Record<string, any>): // eslint-disable-next-line @typescript-eslint/no-explicit-any
128
+ Promise<any> | any;
126
129
  }
127
130
  /**
128
131
  * Base interface for callbacks. All methods are optional. If a method is not
@@ -169,6 +172,7 @@ export declare abstract class BaseCallbackHandler extends BaseCallbackHandlerMet
169
172
  ignoreChain: boolean;
170
173
  ignoreAgent: boolean;
171
174
  ignoreRetriever: boolean;
175
+ ignoreCustomEvent: boolean;
172
176
  raiseError: boolean;
173
177
  awaitHandlers: boolean;
174
178
  constructor(input?: BaseCallbackHandlerInput);
@@ -197,6 +201,7 @@ export declare abstract class BaseCallbackHandler extends BaseCallbackHandlerMet
197
201
  ignoreChain: boolean;
198
202
  ignoreAgent: boolean;
199
203
  ignoreRetriever: boolean;
204
+ ignoreCustomEvent: boolean;
200
205
  raiseError: boolean;
201
206
  awaitHandlers: boolean;
202
207
  copy(): BaseCallbackHandler;
@@ -206,7 +211,7 @@ export declare abstract class BaseCallbackHandler extends BaseCallbackHandlerMet
206
211
  * Called at the start of an LLM or Chat Model run, with the prompt(s)
207
212
  * and the run ID.
208
213
  */
209
- handleLLMStart?(llm: Serialized, prompts: string[], runId: string, parentRunId?: string | undefined, extraParams?: Record<string, unknown> | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, name?: string | undefined): any;
214
+ 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;
210
215
  /**
211
216
  * Called when an LLM/ChatModel in `streaming` mode produces a new token
212
217
  */
@@ -223,12 +228,12 @@ export declare abstract class BaseCallbackHandler extends BaseCallbackHandlerMet
223
228
  * Called at the start of a Chat Model run, with the prompt(s)
224
229
  * and the run ID.
225
230
  */
226
- handleChatModelStart?(llm: Serialized, messages: BaseMessage[][], runId: string, parentRunId?: string | undefined, extraParams?: Record<string, unknown> | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, name?: string | undefined): any;
231
+ 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;
227
232
  /**
228
233
  * Called at the start of a Chain run, with the chain name and inputs
229
234
  * and the run ID.
230
235
  */
231
- handleChainStart?(chain: Serialized, inputs: ChainValues, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runType?: string | undefined, name?: string | undefined): any;
236
+ 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;
232
237
  /**
233
238
  * Called if a Chain run encounters an error
234
239
  */
@@ -245,7 +250,7 @@ export declare abstract class BaseCallbackHandler extends BaseCallbackHandlerMet
245
250
  * Called at the start of a Tool run, with the tool name and input
246
251
  * and the run ID.
247
252
  */
248
- handleToolStart?(tool: Serialized, input: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, name?: string | undefined): any;
253
+ handleToolStart?(tool: Serialized, input: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, runName?: string | undefined): any;
249
254
  /**
250
255
  * Called if a Tool run encounters an error
251
256
  */
@@ -253,7 +258,7 @@ export declare abstract class BaseCallbackHandler extends BaseCallbackHandlerMet
253
258
  /**
254
259
  * Called at the end of a Tool run, with the tool output and the run ID.
255
260
  */
256
- handleToolEnd?(output: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;
261
+ handleToolEnd?(output: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;
257
262
  handleText?(text: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): void | Promise<void>;
258
263
  /**
259
264
  * Called when an agent is about to execute an action,
@@ -268,6 +273,7 @@ export declare abstract class BaseCallbackHandler extends BaseCallbackHandlerMet
268
273
  handleRetrieverStart?(retriever: Serialized, query: string, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined, metadata?: Record<string, unknown> | undefined, name?: string | undefined): any;
269
274
  handleRetrieverEnd?(documents: DocumentInterface<Record<string, any>>[], runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;
270
275
  handleRetrieverError?(err: any, runId: string, parentRunId?: string | undefined, tags?: string[] | undefined): any;
276
+ handleCustomEvent?(eventName: string, data: any, runId: string, tags?: string[] | undefined, metadata?: Record<string, any> | undefined): any;
271
277
  };
272
278
  }
273
279
  export {};
@@ -83,6 +83,12 @@ export class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass {
83
83
  writable: true,
84
84
  value: false
85
85
  });
86
+ Object.defineProperty(this, "ignoreCustomEvent", {
87
+ enumerable: true,
88
+ configurable: true,
89
+ writable: true,
90
+ value: false
91
+ });
86
92
  Object.defineProperty(this, "raiseError", {
87
93
  enumerable: true,
88
94
  configurable: true,
@@ -101,6 +107,8 @@ export class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass {
101
107
  this.ignoreChain = input.ignoreChain ?? this.ignoreChain;
102
108
  this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent;
103
109
  this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever;
110
+ this.ignoreCustomEvent =
111
+ input.ignoreCustomEvent ?? this.ignoreCustomEvent;
104
112
  this.raiseError = input.raiseError ?? this.raiseError;
105
113
  this.awaitHandlers =
106
114
  this.raiseError || (input._awaitHandler ?? this.awaitHandlers);
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.dispatchCustomEvent = void 0;
4
+ const node_async_hooks_1 = require("node:async_hooks");
5
+ const web_js_1 = require("./web.cjs");
6
+ const config_js_1 = require("../../runnables/config.cjs");
7
+ const index_js_1 = require("../../singletons/index.cjs");
8
+ /* #__PURE__ */ index_js_1.AsyncLocalStorageProviderSingleton.initializeGlobalInstance(
9
+ /* #__PURE__ */ new node_async_hooks_1.AsyncLocalStorage());
10
+ /**
11
+ * Dispatch a custom event.
12
+ *
13
+ * Note: this method is only supported in non-web environments
14
+ * due to usage of async_hooks to infer config.
15
+ *
16
+ * If you are using this method in the browser, please import and use
17
+ * from "@langchain/core/callbacks/dispatch/web".
18
+ *
19
+ * @param name The name of the custom event.
20
+ * @param payload The data for the custom event.
21
+ * Ideally should be JSON serializable to avoid serialization issues downstream, but not enforced.
22
+ * @param config Optional config object.
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
27
+ *
28
+ * const foo = RunnableLambda.from(async (input: string) => {
29
+ * await dispatchCustomEvent("my_custom_event", { arbitraryField: "someval" });
30
+ * return input;
31
+ * });
32
+ *
33
+ * const callbacks = [{
34
+ * handleCustomEvent: (eventName: string, payload: any) => {
35
+ * // Logs "my_custom_event" and { arbitraryField: "someval" }
36
+ * console.log(eventName, payload);
37
+ * }
38
+ * }];
39
+ *
40
+ * await foo.invoke("hi", { callbacks })
41
+ * ```
42
+ */
43
+ async function dispatchCustomEvent(eventName,
44
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
+ payload, config) {
46
+ const ensuredConfig = (0, config_js_1.ensureConfig)(config);
47
+ await (0, web_js_1.dispatchCustomEvent)(eventName, payload, ensuredConfig);
48
+ }
49
+ exports.dispatchCustomEvent = dispatchCustomEvent;
@@ -0,0 +1,35 @@
1
+ import { type RunnableConfig } from "../../runnables/config.js";
2
+ /**
3
+ * Dispatch a custom event.
4
+ *
5
+ * Note: this method is only supported in non-web environments
6
+ * due to usage of async_hooks to infer config.
7
+ *
8
+ * If you are using this method in the browser, please import and use
9
+ * from "@langchain/core/callbacks/dispatch/web".
10
+ *
11
+ * @param name The name of the custom event.
12
+ * @param payload The data for the custom event.
13
+ * Ideally should be JSON serializable to avoid serialization issues downstream, but not enforced.
14
+ * @param config Optional config object.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
19
+ *
20
+ * const foo = RunnableLambda.from(async (input: string) => {
21
+ * await dispatchCustomEvent("my_custom_event", { arbitraryField: "someval" });
22
+ * return input;
23
+ * });
24
+ *
25
+ * const callbacks = [{
26
+ * handleCustomEvent: (eventName: string, payload: any) => {
27
+ * // Logs "my_custom_event" and { arbitraryField: "someval" }
28
+ * console.log(eventName, payload);
29
+ * }
30
+ * }];
31
+ *
32
+ * await foo.invoke("hi", { callbacks })
33
+ * ```
34
+ */
35
+ export declare function dispatchCustomEvent(eventName: string, payload: any, config?: RunnableConfig): Promise<void>;
@@ -0,0 +1,45 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { dispatchCustomEvent as dispatchCustomEventWeb } from "./web.js";
3
+ import { ensureConfig } from "../../runnables/config.js";
4
+ import { AsyncLocalStorageProviderSingleton } from "../../singletons/index.js";
5
+ /* #__PURE__ */ AsyncLocalStorageProviderSingleton.initializeGlobalInstance(
6
+ /* #__PURE__ */ new AsyncLocalStorage());
7
+ /**
8
+ * Dispatch a custom event.
9
+ *
10
+ * Note: this method is only supported in non-web environments
11
+ * due to usage of async_hooks to infer config.
12
+ *
13
+ * If you are using this method in the browser, please import and use
14
+ * from "@langchain/core/callbacks/dispatch/web".
15
+ *
16
+ * @param name The name of the custom event.
17
+ * @param payload The data for the custom event.
18
+ * Ideally should be JSON serializable to avoid serialization issues downstream, but not enforced.
19
+ * @param config Optional config object.
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
24
+ *
25
+ * const foo = RunnableLambda.from(async (input: string) => {
26
+ * await dispatchCustomEvent("my_custom_event", { arbitraryField: "someval" });
27
+ * return input;
28
+ * });
29
+ *
30
+ * const callbacks = [{
31
+ * handleCustomEvent: (eventName: string, payload: any) => {
32
+ * // Logs "my_custom_event" and { arbitraryField: "someval" }
33
+ * console.log(eventName, payload);
34
+ * }
35
+ * }];
36
+ *
37
+ * await foo.invoke("hi", { callbacks })
38
+ * ```
39
+ */
40
+ export async function dispatchCustomEvent(eventName,
41
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
+ payload, config) {
43
+ const ensuredConfig = ensureConfig(config);
44
+ await dispatchCustomEventWeb(eventName, payload, ensuredConfig);
45
+ }
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.dispatchCustomEvent = void 0;
4
+ const config_js_1 = require("../../runnables/config.cjs");
5
+ /**
6
+ * Dispatch a custom event. Requires an explicit config object.
7
+ * @param name The name of the custom event.
8
+ * @param payload The data for the custom event.
9
+ * Ideally should be JSON serializable to avoid serialization issues downstream, but not enforced.
10
+ * @param config Config object.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
15
+ *
16
+ * const foo = RunnableLambda.from(async (input: string, config?: RunnableConfig) => {
17
+ * await dispatchCustomEvent(
18
+ * "my_custom_event",
19
+ * { arbitraryField: "someval" },
20
+ * config
21
+ * );
22
+ * return input;
23
+ * });
24
+ *
25
+ * const callbacks = [{
26
+ * handleCustomEvent: (eventName: string, payload: any) => {
27
+ * // Logs "my_custom_event" and { arbitraryField: "someval" }
28
+ * console.log(eventName, payload);
29
+ * }
30
+ * }];
31
+ *
32
+ * await foo.invoke("hi", { callbacks })
33
+ * ```
34
+ */
35
+ async function dispatchCustomEvent(name,
36
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
+ payload, config) {
38
+ const callbackManager = await (0, config_js_1.getCallbackManagerForConfig)(config);
39
+ const parentRunId = callbackManager?.getParentRunId();
40
+ // We want to get the callback manager for the parent run.
41
+ // This is a work-around for now to be able to dispatch adhoc events from
42
+ // within a tool or a lambda and have the metadata events associated
43
+ // with the parent run rather than have a new run id generated for each.
44
+ if (callbackManager === undefined || parentRunId === undefined) {
45
+ throw new Error([
46
+ "Unable to dispatch a custom event without a parent run id.",
47
+ "This function can only be called from within an existing run (e.g.,",
48
+ "inside a tool or a RunnableLambda).",
49
+ `\n\nIf you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,
50
+ "and explicitly pass in a config parameter.",
51
+ `\n\nOr, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,
52
+ "\n |",
53
+ "\n └-> https://js.langchain.com/v0.2/docs/how_to/custom_tools#tool-function",
54
+ "\n",
55
+ ].join(" "));
56
+ }
57
+ // We pass parent id as the current run id here intentionally since events dispatch
58
+ // from within things like RunnableLambda
59
+ await callbackManager.handleCustomEvent?.(name, payload, parentRunId);
60
+ }
61
+ exports.dispatchCustomEvent = dispatchCustomEvent;
@@ -0,0 +1,32 @@
1
+ import { type RunnableConfig } from "../../runnables/config.js";
2
+ /**
3
+ * Dispatch a custom event. Requires an explicit config object.
4
+ * @param name The name of the custom event.
5
+ * @param payload The data for the custom event.
6
+ * Ideally should be JSON serializable to avoid serialization issues downstream, but not enforced.
7
+ * @param config Config object.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
12
+ *
13
+ * const foo = RunnableLambda.from(async (input: string, config?: RunnableConfig) => {
14
+ * await dispatchCustomEvent(
15
+ * "my_custom_event",
16
+ * { arbitraryField: "someval" },
17
+ * config
18
+ * );
19
+ * return input;
20
+ * });
21
+ *
22
+ * const callbacks = [{
23
+ * handleCustomEvent: (eventName: string, payload: any) => {
24
+ * // Logs "my_custom_event" and { arbitraryField: "someval" }
25
+ * console.log(eventName, payload);
26
+ * }
27
+ * }];
28
+ *
29
+ * await foo.invoke("hi", { callbacks })
30
+ * ```
31
+ */
32
+ export declare function dispatchCustomEvent(name: string, payload: any, config?: RunnableConfig): Promise<void>;
@@ -0,0 +1,57 @@
1
+ import { getCallbackManagerForConfig, } from "../../runnables/config.js";
2
+ /**
3
+ * Dispatch a custom event. Requires an explicit config object.
4
+ * @param name The name of the custom event.
5
+ * @param payload The data for the custom event.
6
+ * Ideally should be JSON serializable to avoid serialization issues downstream, but not enforced.
7
+ * @param config Config object.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
12
+ *
13
+ * const foo = RunnableLambda.from(async (input: string, config?: RunnableConfig) => {
14
+ * await dispatchCustomEvent(
15
+ * "my_custom_event",
16
+ * { arbitraryField: "someval" },
17
+ * config
18
+ * );
19
+ * return input;
20
+ * });
21
+ *
22
+ * const callbacks = [{
23
+ * handleCustomEvent: (eventName: string, payload: any) => {
24
+ * // Logs "my_custom_event" and { arbitraryField: "someval" }
25
+ * console.log(eventName, payload);
26
+ * }
27
+ * }];
28
+ *
29
+ * await foo.invoke("hi", { callbacks })
30
+ * ```
31
+ */
32
+ export async function dispatchCustomEvent(name,
33
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
34
+ payload, config) {
35
+ const callbackManager = await getCallbackManagerForConfig(config);
36
+ const parentRunId = callbackManager?.getParentRunId();
37
+ // We want to get the callback manager for the parent run.
38
+ // This is a work-around for now to be able to dispatch adhoc events from
39
+ // within a tool or a lambda and have the metadata events associated
40
+ // with the parent run rather than have a new run id generated for each.
41
+ if (callbackManager === undefined || parentRunId === undefined) {
42
+ throw new Error([
43
+ "Unable to dispatch a custom event without a parent run id.",
44
+ "This function can only be called from within an existing run (e.g.,",
45
+ "inside a tool or a RunnableLambda).",
46
+ `\n\nIf you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,
47
+ "and explicitly pass in a config parameter.",
48
+ `\n\nOr, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,
49
+ "\n |",
50
+ "\n └-> https://js.langchain.com/v0.2/docs/how_to/custom_tools#tool-function",
51
+ "\n",
52
+ ].join(" "));
53
+ }
54
+ // We pass parent id as the current run id here intentionally since events dispatch
55
+ // from within things like RunnableLambda
56
+ await callbackManager.handleCustomEvent?.(name, payload, parentRunId);
57
+ }
@@ -308,6 +308,7 @@ class CallbackManagerForToolRun extends BaseRunManager {
308
308
  }
309
309
  }, handler.awaitHandlers)));
310
310
  }
311
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
311
312
  async handleToolEnd(output) {
312
313
  await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => {
313
314
  if (!handler.ignoreAgent) {
@@ -506,6 +507,25 @@ class CallbackManager extends BaseCallbackManager {
506
507
  }, handler.awaitHandlers)));
507
508
  return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
508
509
  }
510
+ async handleCustomEvent(eventName,
511
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
512
+ data, runId, _tags,
513
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
514
+ _metadata) {
515
+ await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => {
516
+ if (!handler.ignoreCustomEvent) {
517
+ try {
518
+ await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata);
519
+ }
520
+ catch (err) {
521
+ console.error(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`);
522
+ if (handler.raiseError) {
523
+ throw err;
524
+ }
525
+ }
526
+ }
527
+ }, handler.awaitHandlers)));
528
+ }
509
529
  addHandler(handler, inherit = true) {
510
530
  this.handlers.push(handler);
511
531
  if (inherit) {