@langchain/core 0.2.17 → 0.2.18-rc.0

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.
@@ -9,8 +9,9 @@ const env_js_1 = require("../utils/env.cjs");
9
9
  const tracer_langchain_js_1 = require("../tracers/tracer_langchain.cjs");
10
10
  const promises_js_1 = require("./promises.cjs");
11
11
  const callbacks_js_1 = require("../utils/callbacks.cjs");
12
+ const base_js_2 = require("../tracers/base.cjs");
12
13
  if (
13
- /* #__PURE__ */ (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_TRACING_V2") === "true" &&
14
+ /* #__PURE__ */ (0, callbacks_js_1.isTracingEnabled)() &&
14
15
  /* #__PURE__ */ (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_CALLBACKS_BACKGROUND") !==
15
16
  "true") {
16
17
  /* #__PURE__ */ console.warn([
@@ -417,8 +418,17 @@ class CallbackManager extends BaseCallbackManager {
417
418
  return Promise.all(prompts.map(async (prompt, idx) => {
418
419
  // Can't have duplicate runs with the same run ID (if provided)
419
420
  const runId_ = idx === 0 && runId ? runId : (0, uuid_1.v4)();
420
- await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => {
421
- if (!handler.ignoreLLM) {
421
+ await Promise.all(this.handlers.map((handler) => {
422
+ if (handler.ignoreLLM) {
423
+ return;
424
+ }
425
+ if ((0, base_js_2.isBaseTracer)(handler)) {
426
+ // Create and add run to the run map.
427
+ // We do this synchronously to avoid race conditions
428
+ // when callbacks are backgrounded.
429
+ handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
430
+ }
431
+ return (0, promises_js_1.consumeCallback)(async () => {
422
432
  try {
423
433
  await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
424
434
  }
@@ -428,8 +438,8 @@ class CallbackManager extends BaseCallbackManager {
428
438
  throw err;
429
439
  }
430
440
  }
431
- }
432
- }, handler.awaitHandlers)));
441
+ }, handler.awaitHandlers);
442
+ }));
433
443
  return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
434
444
  }));
435
445
  }
@@ -437,8 +447,17 @@ class CallbackManager extends BaseCallbackManager {
437
447
  return Promise.all(messages.map(async (messageGroup, idx) => {
438
448
  // Can't have duplicate runs with the same run ID (if provided)
439
449
  const runId_ = idx === 0 && runId ? runId : (0, uuid_1.v4)();
440
- await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => {
441
- if (!handler.ignoreLLM) {
450
+ await Promise.all(this.handlers.map((handler) => {
451
+ if (handler.ignoreLLM) {
452
+ return;
453
+ }
454
+ if ((0, base_js_2.isBaseTracer)(handler)) {
455
+ // Create and add run to the run map.
456
+ // We do this synchronously to avoid race conditions
457
+ // when callbacks are backgrounded.
458
+ handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
459
+ }
460
+ return (0, promises_js_1.consumeCallback)(async () => {
442
461
  try {
443
462
  if (handler.handleChatModelStart) {
444
463
  await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
@@ -454,14 +473,23 @@ class CallbackManager extends BaseCallbackManager {
454
473
  throw err;
455
474
  }
456
475
  }
457
- }
458
- }, handler.awaitHandlers)));
476
+ }, handler.awaitHandlers);
477
+ }));
459
478
  return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
460
479
  }));
461
480
  }
462
481
  async handleChainStart(chain, inputs, runId = (0, uuid_1.v4)(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
463
- await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => {
464
- if (!handler.ignoreChain) {
482
+ await Promise.all(this.handlers.map((handler) => {
483
+ if (handler.ignoreChain) {
484
+ return;
485
+ }
486
+ if ((0, base_js_2.isBaseTracer)(handler)) {
487
+ // Create and add run to the run map.
488
+ // We do this synchronously to avoid race conditions
489
+ // when callbacks are backgrounded.
490
+ handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);
491
+ }
492
+ return (0, promises_js_1.consumeCallback)(async () => {
465
493
  try {
466
494
  await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);
467
495
  }
@@ -471,13 +499,22 @@ class CallbackManager extends BaseCallbackManager {
471
499
  throw err;
472
500
  }
473
501
  }
474
- }
475
- }, handler.awaitHandlers)));
502
+ }, handler.awaitHandlers);
503
+ }));
476
504
  return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
477
505
  }
478
506
  async handleToolStart(tool, input, runId = (0, uuid_1.v4)(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
479
- await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => {
480
- if (!handler.ignoreAgent) {
507
+ await Promise.all(this.handlers.map((handler) => {
508
+ if (handler.ignoreAgent) {
509
+ return;
510
+ }
511
+ if ((0, base_js_2.isBaseTracer)(handler)) {
512
+ // Create and add run to the run map.
513
+ // We do this synchronously to avoid race conditions
514
+ // when callbacks are backgrounded.
515
+ handler._createRunForToolStart(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName);
516
+ }
517
+ return (0, promises_js_1.consumeCallback)(async () => {
481
518
  try {
482
519
  await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName);
483
520
  }
@@ -487,13 +524,22 @@ class CallbackManager extends BaseCallbackManager {
487
524
  throw err;
488
525
  }
489
526
  }
490
- }
491
- }, handler.awaitHandlers)));
527
+ }, handler.awaitHandlers);
528
+ }));
492
529
  return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
493
530
  }
494
531
  async handleRetrieverStart(retriever, query, runId = (0, uuid_1.v4)(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
495
- await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => {
496
- if (!handler.ignoreRetriever) {
532
+ await Promise.all(this.handlers.map((handler) => {
533
+ if (handler.ignoreRetriever) {
534
+ return;
535
+ }
536
+ if ((0, base_js_2.isBaseTracer)(handler)) {
537
+ // Create and add run to the run map.
538
+ // We do this synchronously to avoid race conditions
539
+ // when callbacks are backgrounded.
540
+ handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName);
541
+ }
542
+ return (0, promises_js_1.consumeCallback)(async () => {
497
543
  try {
498
544
  await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName);
499
545
  }
@@ -503,8 +549,8 @@ class CallbackManager extends BaseCallbackManager {
503
549
  throw err;
504
550
  }
505
551
  }
506
- }
507
- }, handler.awaitHandlers)));
552
+ }, handler.awaitHandlers);
553
+ }));
508
554
  return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
509
555
  }
510
556
  async handleCustomEvent(eventName,
@@ -629,7 +675,8 @@ class CallbackManager extends BaseCallbackManager {
629
675
  }
630
676
  const verboseEnabled = (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_VERBOSE") === "true" ||
631
677
  options?.verbose;
632
- const tracingV2Enabled = (0, callbacks_js_1.isTracingEnabled)();
678
+ const tracingV2Enabled = tracer_langchain_js_1.LangChainTracer.getTraceableRunTree()?.tracingEnabled ||
679
+ (0, callbacks_js_1.isTracingEnabled)();
633
680
  const tracingEnabled = tracingV2Enabled ||
634
681
  ((0, env_js_1.getEnvironmentVariable)("LANGCHAIN_TRACING") ?? false);
635
682
  if (verboseEnabled || tracingEnabled) {
@@ -649,7 +696,8 @@ class CallbackManager extends BaseCallbackManager {
649
696
  // handoff between langchain and langsmith/traceable
650
697
  // override the parent run ID
651
698
  callbackManager._parentRunId =
652
- tracerV2.getTraceableRunTree()?.id ?? callbackManager._parentRunId;
699
+ tracer_langchain_js_1.LangChainTracer.getTraceableRunTree()?.id ??
700
+ callbackManager._parentRunId;
653
701
  }
654
702
  }
655
703
  }
@@ -6,8 +6,9 @@ import { getEnvironmentVariable } from "../utils/env.js";
6
6
  import { LangChainTracer, } from "../tracers/tracer_langchain.js";
7
7
  import { consumeCallback } from "./promises.js";
8
8
  import { isTracingEnabled } from "../utils/callbacks.js";
9
+ import { isBaseTracer } from "../tracers/base.js";
9
10
  if (
10
- /* #__PURE__ */ getEnvironmentVariable("LANGCHAIN_TRACING_V2") === "true" &&
11
+ /* #__PURE__ */ isTracingEnabled() &&
11
12
  /* #__PURE__ */ getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") !==
12
13
  "true") {
13
14
  /* #__PURE__ */ console.warn([
@@ -407,8 +408,17 @@ export class CallbackManager extends BaseCallbackManager {
407
408
  return Promise.all(prompts.map(async (prompt, idx) => {
408
409
  // Can't have duplicate runs with the same run ID (if provided)
409
410
  const runId_ = idx === 0 && runId ? runId : uuidv4();
410
- await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
411
- if (!handler.ignoreLLM) {
411
+ await Promise.all(this.handlers.map((handler) => {
412
+ if (handler.ignoreLLM) {
413
+ return;
414
+ }
415
+ if (isBaseTracer(handler)) {
416
+ // Create and add run to the run map.
417
+ // We do this synchronously to avoid race conditions
418
+ // when callbacks are backgrounded.
419
+ handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
420
+ }
421
+ return consumeCallback(async () => {
412
422
  try {
413
423
  await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
414
424
  }
@@ -418,8 +428,8 @@ export class CallbackManager extends BaseCallbackManager {
418
428
  throw err;
419
429
  }
420
430
  }
421
- }
422
- }, handler.awaitHandlers)));
431
+ }, handler.awaitHandlers);
432
+ }));
423
433
  return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
424
434
  }));
425
435
  }
@@ -427,8 +437,17 @@ export class CallbackManager extends BaseCallbackManager {
427
437
  return Promise.all(messages.map(async (messageGroup, idx) => {
428
438
  // Can't have duplicate runs with the same run ID (if provided)
429
439
  const runId_ = idx === 0 && runId ? runId : uuidv4();
430
- await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
431
- if (!handler.ignoreLLM) {
440
+ await Promise.all(this.handlers.map((handler) => {
441
+ if (handler.ignoreLLM) {
442
+ return;
443
+ }
444
+ if (isBaseTracer(handler)) {
445
+ // Create and add run to the run map.
446
+ // We do this synchronously to avoid race conditions
447
+ // when callbacks are backgrounded.
448
+ handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
449
+ }
450
+ return consumeCallback(async () => {
432
451
  try {
433
452
  if (handler.handleChatModelStart) {
434
453
  await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);
@@ -444,14 +463,23 @@ export class CallbackManager extends BaseCallbackManager {
444
463
  throw err;
445
464
  }
446
465
  }
447
- }
448
- }, handler.awaitHandlers)));
466
+ }, handler.awaitHandlers);
467
+ }));
449
468
  return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
450
469
  }));
451
470
  }
452
471
  async handleChainStart(chain, inputs, runId = uuidv4(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
453
- await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
454
- if (!handler.ignoreChain) {
472
+ await Promise.all(this.handlers.map((handler) => {
473
+ if (handler.ignoreChain) {
474
+ return;
475
+ }
476
+ if (isBaseTracer(handler)) {
477
+ // Create and add run to the run map.
478
+ // We do this synchronously to avoid race conditions
479
+ // when callbacks are backgrounded.
480
+ handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);
481
+ }
482
+ return consumeCallback(async () => {
455
483
  try {
456
484
  await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);
457
485
  }
@@ -461,13 +489,22 @@ export class CallbackManager extends BaseCallbackManager {
461
489
  throw err;
462
490
  }
463
491
  }
464
- }
465
- }, handler.awaitHandlers)));
492
+ }, handler.awaitHandlers);
493
+ }));
466
494
  return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
467
495
  }
468
496
  async handleToolStart(tool, input, runId = uuidv4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
469
- await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
470
- if (!handler.ignoreAgent) {
497
+ await Promise.all(this.handlers.map((handler) => {
498
+ if (handler.ignoreAgent) {
499
+ return;
500
+ }
501
+ if (isBaseTracer(handler)) {
502
+ // Create and add run to the run map.
503
+ // We do this synchronously to avoid race conditions
504
+ // when callbacks are backgrounded.
505
+ handler._createRunForToolStart(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName);
506
+ }
507
+ return consumeCallback(async () => {
471
508
  try {
472
509
  await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName);
473
510
  }
@@ -477,13 +514,22 @@ export class CallbackManager extends BaseCallbackManager {
477
514
  throw err;
478
515
  }
479
516
  }
480
- }
481
- }, handler.awaitHandlers)));
517
+ }, handler.awaitHandlers);
518
+ }));
482
519
  return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
483
520
  }
484
521
  async handleRetrieverStart(retriever, query, runId = uuidv4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
485
- await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
486
- if (!handler.ignoreRetriever) {
522
+ await Promise.all(this.handlers.map((handler) => {
523
+ if (handler.ignoreRetriever) {
524
+ return;
525
+ }
526
+ if (isBaseTracer(handler)) {
527
+ // Create and add run to the run map.
528
+ // We do this synchronously to avoid race conditions
529
+ // when callbacks are backgrounded.
530
+ handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName);
531
+ }
532
+ return consumeCallback(async () => {
487
533
  try {
488
534
  await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName);
489
535
  }
@@ -493,8 +539,8 @@ export class CallbackManager extends BaseCallbackManager {
493
539
  throw err;
494
540
  }
495
541
  }
496
- }
497
- }, handler.awaitHandlers)));
542
+ }, handler.awaitHandlers);
543
+ }));
498
544
  return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
499
545
  }
500
546
  async handleCustomEvent(eventName,
@@ -619,7 +665,8 @@ export class CallbackManager extends BaseCallbackManager {
619
665
  }
620
666
  const verboseEnabled = getEnvironmentVariable("LANGCHAIN_VERBOSE") === "true" ||
621
667
  options?.verbose;
622
- const tracingV2Enabled = isTracingEnabled();
668
+ const tracingV2Enabled = LangChainTracer.getTraceableRunTree()?.tracingEnabled ||
669
+ isTracingEnabled();
623
670
  const tracingEnabled = tracingV2Enabled ||
624
671
  (getEnvironmentVariable("LANGCHAIN_TRACING") ?? false);
625
672
  if (verboseEnabled || tracingEnabled) {
@@ -639,7 +686,8 @@ export class CallbackManager extends BaseCallbackManager {
639
686
  // handoff between langchain and langsmith/traceable
640
687
  // override the parent run ID
641
688
  callbackManager._parentRunId =
642
- tracerV2.getTraceableRunTree()?.id ?? callbackManager._parentRunId;
689
+ LangChainTracer.getTraceableRunTree()?.id ??
690
+ callbackManager._parentRunId;
643
691
  }
644
692
  }
645
693
  }
@@ -1,3 +1,4 @@
1
+ /* eslint-disable no-promise-executor-return */
1
2
  import { test, expect } from "@jest/globals";
2
3
  import * as uuid from "uuid";
3
4
  import { CallbackManager } from "../manager.js";
@@ -227,6 +228,8 @@ test("CallbackManager", async () => {
227
228
  new Document({ pageContent: "test", metadata: { test: "test" } }),
228
229
  ]);
229
230
  await retrieverCb.handleRetrieverError(new Error("test"));
231
+ // In case background mode is on while running this test
232
+ await new Promise((resolve) => setTimeout(resolve, 100));
230
233
  for (const handler of [handler1, handler2]) {
231
234
  expect(handler.starts).toBe(5);
232
235
  expect(handler.ends).toBe(5);
@@ -1508,7 +1508,7 @@ class RunnableLambda extends Runnable {
1508
1508
  callbacks: runManager?.getChild(),
1509
1509
  recursionLimit: (config?.recursionLimit ?? config_js_1.DEFAULT_RECURSION_LIMIT) - 1,
1510
1510
  });
1511
- void index_js_1.AsyncLocalStorageProviderSingleton.getInstance().run(childConfig, async () => {
1511
+ void index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {
1512
1512
  try {
1513
1513
  let output = await this.func(input, {
1514
1514
  ...childConfig,
@@ -1594,7 +1594,7 @@ class RunnableLambda extends Runnable {
1594
1594
  recursionLimit: (config?.recursionLimit ?? config_js_1.DEFAULT_RECURSION_LIMIT) - 1,
1595
1595
  });
1596
1596
  const output = await new Promise((resolve, reject) => {
1597
- void index_js_1.AsyncLocalStorageProviderSingleton.getInstance().run(childConfig, async () => {
1597
+ void index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {
1598
1598
  try {
1599
1599
  const res = await this.func(finalChunk, {
1600
1600
  ...childConfig,
@@ -202,11 +202,11 @@ export declare abstract class Runnable<RunInput = any, RunOutput = any, CallOpti
202
202
  * +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
203
203
  * | on_llm_end | [model name] | | 'Hello human!' | |
204
204
  * +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
205
- * | on_chain_start | format_docs | | | |
205
+ * | on_chain_start | some_runnable | | | |
206
206
  * +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
207
- * | on_chain_stream | format_docs | "hello world!, goodbye world!" | | |
207
+ * | on_chain_stream | some_runnable | "hello world!, goodbye world!" | | |
208
208
  * +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
209
- * | on_chain_end | format_docs | | [Document(...)] | "hello world!, goodbye world!" |
209
+ * | on_chain_end | some_runnable | | [Document(...)] | "hello world!, goodbye world!" |
210
210
  * +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
211
211
  * | on_tool_start | some_tool | | {"x": 1, "y": "2"} | |
212
212
  * +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
@@ -220,6 +220,52 @@ export declare abstract class Runnable<RunInput = any, RunOutput = any, CallOpti
220
220
  * +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
221
221
  * | on_prompt_end | [template_name] | | {"question": "hello"} | ChatPromptValue(messages: [SystemMessage, ...]) |
222
222
  * +----------------------+------------------+---------------------------------+-----------------------------------------------+-------------------------------------------------+
223
+ *
224
+ * The "on_chain_*" events are the default for Runnables that don't fit one of the above categories.
225
+ *
226
+ * In addition to the standard events above, users can also dispatch custom events.
227
+ *
228
+ * Custom events will be only be surfaced with in the `v2` version of the API!
229
+ *
230
+ * A custom event has following format:
231
+ *
232
+ * +-----------+------+-----------------------------------------------------------------------------------------------------------+
233
+ * | Attribute | Type | Description |
234
+ * +===========+======+===========================================================================================================+
235
+ * | name | str | A user defined name for the event. |
236
+ * +-----------+------+-----------------------------------------------------------------------------------------------------------+
237
+ * | data | Any | The data associated with the event. This can be anything, though we suggest making it JSON serializable. |
238
+ * +-----------+------+-----------------------------------------------------------------------------------------------------------+
239
+ *
240
+ * Here's an example:
241
+ * @example
242
+ * ```ts
243
+ * import { RunnableLambda } from "@langchain/core/runnables";
244
+ * import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
245
+ * // Use this import for web environments that don't support "async_hooks"
246
+ * // and manually pass config to child runs.
247
+ * // import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch/web";
248
+ *
249
+ * const slowThing = RunnableLambda.from(async (someInput: string) => {
250
+ * // Placeholder for some slow operation
251
+ * await new Promise((resolve) => setTimeout(resolve, 100));
252
+ * await dispatchCustomEvent("progress_event", {
253
+ * message: "Finished step 1 of 2",
254
+ * });
255
+ * await new Promise((resolve) => setTimeout(resolve, 100));
256
+ * return "Done";
257
+ * });
258
+ *
259
+ * const eventStream = await slowThing.streamEvents("hello world", {
260
+ * version: "v2",
261
+ * });
262
+ *
263
+ * for await (const event of eventStream) {
264
+ * if (event.event === "on_custom_event") {
265
+ * console.log(event);
266
+ * }
267
+ * }
268
+ * ```
223
269
  */
224
270
  streamEvents(input: RunInput, options: Partial<CallOptions> & {
225
271
  version: "v1" | "v2";
@@ -1494,7 +1494,7 @@ export class RunnableLambda extends Runnable {
1494
1494
  callbacks: runManager?.getChild(),
1495
1495
  recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1,
1496
1496
  });
1497
- void AsyncLocalStorageProviderSingleton.getInstance().run(childConfig, async () => {
1497
+ void AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {
1498
1498
  try {
1499
1499
  let output = await this.func(input, {
1500
1500
  ...childConfig,
@@ -1580,7 +1580,7 @@ export class RunnableLambda extends Runnable {
1580
1580
  recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1,
1581
1581
  });
1582
1582
  const output = await new Promise((resolve, reject) => {
1583
- void AsyncLocalStorageProviderSingleton.getInstance().run(childConfig, async () => {
1583
+ void AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {
1584
1584
  try {
1585
1585
  const res = await this.func(finalChunk, {
1586
1586
  ...childConfig,
@@ -5,7 +5,7 @@ const manager_js_1 = require("../callbacks/manager.cjs");
5
5
  const index_js_1 = require("../singletons/index.cjs");
6
6
  exports.DEFAULT_RECURSION_LIMIT = 25;
7
7
  async function getCallbackManagerForConfig(config) {
8
- return manager_js_1.CallbackManager.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata);
8
+ return manager_js_1.CallbackManager._configureSync(config?.callbacks, undefined, config?.tags, undefined, config?.metadata);
9
9
  }
10
10
  exports.getCallbackManagerForConfig = getCallbackManagerForConfig;
11
11
  function mergeConfigs(...configs) {
@@ -84,12 +84,9 @@ exports.mergeConfigs = mergeConfigs;
84
84
  const PRIMITIVES = new Set(["string", "number", "boolean"]);
85
85
  /**
86
86
  * Ensure that a passed config is an object with all required keys present.
87
- *
88
- * Note: To make sure async local storage loading works correctly, this
89
- * should not be called with a default or prepopulated config argument.
90
87
  */
91
88
  function ensureConfig(config) {
92
- const implicitConfig = index_js_1.AsyncLocalStorageProviderSingleton.getInstance().getStore();
89
+ const implicitConfig = index_js_1.AsyncLocalStorageProviderSingleton.getRunnableConfig();
93
90
  let empty = {
94
91
  tags: [],
95
92
  metadata: {},
@@ -97,10 +94,10 @@ function ensureConfig(config) {
97
94
  runId: undefined,
98
95
  };
99
96
  if (implicitConfig) {
100
- // Don't allow runId to be loaded implicitly, as this can cause
97
+ // Don't allow runId and runName to be loaded implicitly, as this can cause
101
98
  // child runs to improperly inherit their parents' run ids.
102
99
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
103
- const { runId, ...rest } = implicitConfig;
100
+ const { runId, runName, ...rest } = implicitConfig;
104
101
  empty = Object.entries(rest).reduce(
105
102
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
106
103
  (currentConfig, [key, value]) => {
@@ -1,25 +1,11 @@
1
- import { type BaseCallbackConfig, CallbackManager } from "../callbacks/manager.js";
1
+ import { CallbackManager } from "../callbacks/manager.js";
2
+ import { RunnableConfig } from "./types.js";
2
3
  export declare const DEFAULT_RECURSION_LIMIT = 25;
3
- export interface RunnableConfig extends BaseCallbackConfig {
4
- /**
5
- * Runtime values for attributes previously made configurable on this Runnable,
6
- * or sub-Runnables.
7
- */
8
- configurable?: Record<string, any>;
9
- /**
10
- * Maximum number of times a call can recurse. If not provided, defaults to 25.
11
- */
12
- recursionLimit?: number;
13
- /** Maximum number of parallel calls to make. */
14
- maxConcurrency?: number;
15
- }
4
+ export { type RunnableConfig };
16
5
  export declare function getCallbackManagerForConfig(config?: RunnableConfig): Promise<CallbackManager | undefined>;
17
6
  export declare function mergeConfigs<CallOptions extends RunnableConfig>(...configs: (CallOptions | RunnableConfig | undefined | null)[]): Partial<CallOptions>;
18
7
  /**
19
8
  * Ensure that a passed config is an object with all required keys present.
20
- *
21
- * Note: To make sure async local storage loading works correctly, this
22
- * should not be called with a default or prepopulated config argument.
23
9
  */
24
10
  export declare function ensureConfig<CallOptions extends RunnableConfig>(config?: CallOptions): CallOptions;
25
11
  /**
@@ -1,8 +1,8 @@
1
- import { CallbackManager, ensureHandler, } from "../callbacks/manager.js";
1
+ import { CallbackManager, ensureHandler } from "../callbacks/manager.js";
2
2
  import { AsyncLocalStorageProviderSingleton } from "../singletons/index.js";
3
3
  export const DEFAULT_RECURSION_LIMIT = 25;
4
4
  export async function getCallbackManagerForConfig(config) {
5
- return CallbackManager.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata);
5
+ return CallbackManager._configureSync(config?.callbacks, undefined, config?.tags, undefined, config?.metadata);
6
6
  }
7
7
  export function mergeConfigs(...configs) {
8
8
  // We do not want to call ensureConfig on the empty state here as this may cause
@@ -79,12 +79,9 @@ export function mergeConfigs(...configs) {
79
79
  const PRIMITIVES = new Set(["string", "number", "boolean"]);
80
80
  /**
81
81
  * Ensure that a passed config is an object with all required keys present.
82
- *
83
- * Note: To make sure async local storage loading works correctly, this
84
- * should not be called with a default or prepopulated config argument.
85
82
  */
86
83
  export function ensureConfig(config) {
87
- const implicitConfig = AsyncLocalStorageProviderSingleton.getInstance().getStore();
84
+ const implicitConfig = AsyncLocalStorageProviderSingleton.getRunnableConfig();
88
85
  let empty = {
89
86
  tags: [],
90
87
  metadata: {},
@@ -92,10 +89,10 @@ export function ensureConfig(config) {
92
89
  runId: undefined,
93
90
  };
94
91
  if (implicitConfig) {
95
- // Don't allow runId to be loaded implicitly, as this can cause
92
+ // Don't allow runId and runName to be loaded implicitly, as this can cause
96
93
  // child runs to improperly inherit their parents' run ids.
97
94
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
98
- const { runId, ...rest } = implicitConfig;
95
+ const { runId, runName, ...rest } = implicitConfig;
99
96
  empty = Object.entries(rest).reduce(
100
97
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
101
98
  (currentConfig, [key, value]) => {
@@ -15,7 +15,7 @@ export declare class Graph {
15
15
  */
16
16
  extend(graph: Graph, prefix?: string): ({
17
17
  id: string;
18
- data: RunnableIOSchema | RunnableInterface<any, any, import("./config.js").RunnableConfig>;
18
+ data: RunnableIOSchema | RunnableInterface<any, any, import("./types.js").RunnableConfig>;
19
19
  } | undefined)[];
20
20
  trimFirstNode(): void;
21
21
  trimLastNode(): void;
@@ -23,9 +23,8 @@ function isAsyncIterable(thing) {
23
23
  }
24
24
  exports.isAsyncIterable = isAsyncIterable;
25
25
  function* consumeIteratorInContext(context, iter) {
26
- const storage = index_js_1.AsyncLocalStorageProviderSingleton.getInstance();
27
26
  while (true) {
28
- const { value, done } = storage.run(context, iter.next.bind(iter));
27
+ const { value, done } = index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig(context, iter.next.bind(iter), true);
29
28
  if (done) {
30
29
  break;
31
30
  }
@@ -36,10 +35,9 @@ function* consumeIteratorInContext(context, iter) {
36
35
  }
37
36
  exports.consumeIteratorInContext = consumeIteratorInContext;
38
37
  async function* consumeAsyncIterableInContext(context, iter) {
39
- const storage = index_js_1.AsyncLocalStorageProviderSingleton.getInstance();
40
38
  const iterator = iter[Symbol.asyncIterator]();
41
39
  while (true) {
42
- const { value, done } = await storage.run(context, iterator.next.bind(iter));
40
+ const { value, done } = await index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig(context, iterator.next.bind(iter), true);
43
41
  if (done) {
44
42
  break;
45
43
  }
@@ -17,9 +17,8 @@ export function isAsyncIterable(thing) {
17
17
  "function");
18
18
  }
19
19
  export function* consumeIteratorInContext(context, iter) {
20
- const storage = AsyncLocalStorageProviderSingleton.getInstance();
21
20
  while (true) {
22
- const { value, done } = storage.run(context, iter.next.bind(iter));
21
+ const { value, done } = AsyncLocalStorageProviderSingleton.runWithConfig(context, iter.next.bind(iter), true);
23
22
  if (done) {
24
23
  break;
25
24
  }
@@ -29,10 +28,9 @@ export function* consumeIteratorInContext(context, iter) {
29
28
  }
30
29
  }
31
30
  export async function* consumeAsyncIterableInContext(context, iter) {
32
- const storage = AsyncLocalStorageProviderSingleton.getInstance();
33
31
  const iterator = iter[Symbol.asyncIterator]();
34
32
  while (true) {
35
- const { value, done } = await storage.run(context, iterator.next.bind(iter));
33
+ const { value, done } = await AsyncLocalStorageProviderSingleton.runWithConfig(context, iterator.next.bind(iter), true);
36
34
  if (done) {
37
35
  break;
38
36
  }