@langchain/core 0.3.21 → 0.3.23

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 (81) hide show
  1. package/dist/callbacks/base.cjs +9 -1
  2. package/dist/callbacks/base.d.ts +1 -0
  3. package/dist/callbacks/base.js +7 -0
  4. package/dist/callbacks/manager.cjs +18 -0
  5. package/dist/callbacks/manager.js +19 -1
  6. package/dist/context.cjs +13 -123
  7. package/dist/context.d.ts +2 -101
  8. package/dist/context.js +9 -119
  9. package/dist/messages/tool.cjs +14 -1
  10. package/dist/messages/tool.d.ts +13 -1
  11. package/dist/messages/tool.js +12 -0
  12. package/dist/output_parsers/transform.cjs +2 -2
  13. package/dist/output_parsers/transform.js +1 -1
  14. package/dist/runnables/base.cjs +2 -2
  15. package/dist/runnables/base.d.ts +1 -2
  16. package/dist/runnables/base.js +3 -3
  17. package/dist/runnables/config.cjs +17 -1
  18. package/dist/runnables/config.d.ts +1 -0
  19. package/dist/runnables/config.js +15 -0
  20. package/dist/runnables/index.cjs +2 -1
  21. package/dist/runnables/index.d.ts +1 -1
  22. package/dist/runnables/index.js +1 -1
  23. package/dist/runnables/iter.cjs +3 -2
  24. package/dist/runnables/iter.d.ts +1 -1
  25. package/dist/runnables/iter.js +3 -2
  26. package/dist/runnables/types.d.ts +1 -1
  27. package/dist/singletons/async_local_storage/context.cjs +189 -0
  28. package/dist/singletons/async_local_storage/context.d.ts +155 -0
  29. package/dist/singletons/async_local_storage/context.js +182 -0
  30. package/dist/singletons/async_local_storage/globals.cjs +2 -1
  31. package/dist/singletons/async_local_storage/globals.d.ts +2 -1
  32. package/dist/singletons/async_local_storage/globals.js +1 -0
  33. package/dist/singletons/async_local_storage/index.cjs +4 -5
  34. package/dist/singletons/async_local_storage/index.d.ts +0 -1
  35. package/dist/singletons/async_local_storage/index.js +1 -2
  36. package/dist/singletons/callbacks.cjs +6 -4
  37. package/dist/singletons/callbacks.js +6 -4
  38. package/dist/singletons/index.cjs +3 -3
  39. package/dist/singletons/index.d.ts +4 -2
  40. package/dist/singletons/index.js +4 -3
  41. package/dist/tools/index.cjs +14 -12
  42. package/dist/tools/index.d.ts +11 -8
  43. package/dist/tools/index.js +16 -14
  44. package/dist/types/stream.d.ts +1 -0
  45. package/dist/utils/json_schema.cjs +3 -3
  46. package/dist/utils/json_schema.d.ts +1 -1
  47. package/dist/utils/json_schema.js +1 -1
  48. package/dist/utils/stream.cjs +3 -2
  49. package/dist/utils/stream.d.ts +2 -1
  50. package/dist/utils/stream.js +3 -2
  51. package/package.json +2 -1
  52. package/dist/utils/@cfworker/json-schema/index.cjs +0 -17
  53. package/dist/utils/@cfworker/json-schema/index.d.ts +0 -1
  54. package/dist/utils/@cfworker/json-schema/index.js +0 -1
  55. package/dist/utils/@cfworker/json-schema/src/deep-compare-strict.cjs +0 -43
  56. package/dist/utils/@cfworker/json-schema/src/deep-compare-strict.d.ts +0 -1
  57. package/dist/utils/@cfworker/json-schema/src/deep-compare-strict.js +0 -39
  58. package/dist/utils/@cfworker/json-schema/src/dereference.cjs +0 -171
  59. package/dist/utils/@cfworker/json-schema/src/dereference.d.ts +0 -12
  60. package/dist/utils/@cfworker/json-schema/src/dereference.js +0 -167
  61. package/dist/utils/@cfworker/json-schema/src/format.cjs +0 -139
  62. package/dist/utils/@cfworker/json-schema/src/format.d.ts +0 -2
  63. package/dist/utils/@cfworker/json-schema/src/format.js +0 -136
  64. package/dist/utils/@cfworker/json-schema/src/index.cjs +0 -24
  65. package/dist/utils/@cfworker/json-schema/src/index.d.ts +0 -8
  66. package/dist/utils/@cfworker/json-schema/src/index.js +0 -8
  67. package/dist/utils/@cfworker/json-schema/src/pointer.cjs +0 -11
  68. package/dist/utils/@cfworker/json-schema/src/pointer.d.ts +0 -2
  69. package/dist/utils/@cfworker/json-schema/src/pointer.js +0 -6
  70. package/dist/utils/@cfworker/json-schema/src/types.d.ts +0 -72
  71. package/dist/utils/@cfworker/json-schema/src/ucs2-length.cjs +0 -28
  72. package/dist/utils/@cfworker/json-schema/src/ucs2-length.d.ts +0 -6
  73. package/dist/utils/@cfworker/json-schema/src/ucs2-length.js +0 -24
  74. package/dist/utils/@cfworker/json-schema/src/validate.cjs +0 -808
  75. package/dist/utils/@cfworker/json-schema/src/validate.d.ts +0 -3
  76. package/dist/utils/@cfworker/json-schema/src/validate.js +0 -804
  77. package/dist/utils/@cfworker/json-schema/src/validator.cjs +0 -44
  78. package/dist/utils/@cfworker/json-schema/src/validator.d.ts +0 -10
  79. package/dist/utils/@cfworker/json-schema/src/validator.js +0 -40
  80. /package/dist/{utils/@cfworker/json-schema/src/types.cjs → types/stream.cjs} +0 -0
  81. /package/dist/{utils/@cfworker/json-schema/src/types.js → types/stream.js} +0 -0
@@ -0,0 +1,182 @@
1
+ import { isRunTree, RunTree } from "langsmith/run_trees";
2
+ import { _CONTEXT_VARIABLES_KEY, getGlobalAsyncLocalStorageInstance, } from "./globals.js";
3
+ /**
4
+ * Set a context variable. Context variables are scoped to any
5
+ * child runnables called by the current runnable, or globally if set outside
6
+ * of any runnable.
7
+ *
8
+ * @remarks
9
+ * This function is only supported in environments that support AsyncLocalStorage,
10
+ * including Node.js, Deno, and Cloudflare Workers.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { RunnableLambda } from "@langchain/core/runnables";
15
+ * import {
16
+ * getContextVariable,
17
+ * setContextVariable
18
+ * } from "@langchain/core/context";
19
+ *
20
+ * const nested = RunnableLambda.from(() => {
21
+ * // "bar" because it was set by a parent
22
+ * console.log(getContextVariable("foo"));
23
+ *
24
+ * // Override to "baz", but only for child runnables
25
+ * setContextVariable("foo", "baz");
26
+ *
27
+ * // Now "baz", but only for child runnables
28
+ * return getContextVariable("foo");
29
+ * });
30
+ *
31
+ * const runnable = RunnableLambda.from(async () => {
32
+ * // Set a context variable named "foo"
33
+ * setContextVariable("foo", "bar");
34
+ *
35
+ * const res = await nested.invoke({});
36
+ *
37
+ * // Still "bar" since child changes do not affect parents
38
+ * console.log(getContextVariable("foo"));
39
+ *
40
+ * return res;
41
+ * });
42
+ *
43
+ * // undefined, because context variable has not been set yet
44
+ * console.log(getContextVariable("foo"));
45
+ *
46
+ * // Final return value is "baz"
47
+ * const result = await runnable.invoke({});
48
+ * ```
49
+ *
50
+ * @param name The name of the context variable.
51
+ * @param value The value to set.
52
+ */
53
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
54
+ export function setContextVariable(name, value) {
55
+ // Avoid using global singleton due to circuluar dependency issues
56
+ const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();
57
+ if (asyncLocalStorageInstance === undefined) {
58
+ throw new Error(`Internal error: Global shared async local storage instance has not been initialized.`);
59
+ }
60
+ const runTree = asyncLocalStorageInstance.getStore();
61
+ const contextVars = { ...runTree?.[_CONTEXT_VARIABLES_KEY] };
62
+ contextVars[name] = value;
63
+ let newValue = {};
64
+ if (isRunTree(runTree)) {
65
+ newValue = new RunTree(runTree);
66
+ }
67
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
68
+ newValue[_CONTEXT_VARIABLES_KEY] = contextVars;
69
+ asyncLocalStorageInstance.enterWith(newValue);
70
+ }
71
+ /**
72
+ * Get the value of a previously set context variable. Context variables
73
+ * are scoped to any child runnables called by the current runnable,
74
+ * or globally if set outside of any runnable.
75
+ *
76
+ * @remarks
77
+ * This function is only supported in environments that support AsyncLocalStorage,
78
+ * including Node.js, Deno, and Cloudflare Workers.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * import { RunnableLambda } from "@langchain/core/runnables";
83
+ * import {
84
+ * getContextVariable,
85
+ * setContextVariable
86
+ * } from "@langchain/core/context";
87
+ *
88
+ * const nested = RunnableLambda.from(() => {
89
+ * // "bar" because it was set by a parent
90
+ * console.log(getContextVariable("foo"));
91
+ *
92
+ * // Override to "baz", but only for child runnables
93
+ * setContextVariable("foo", "baz");
94
+ *
95
+ * // Now "baz", but only for child runnables
96
+ * return getContextVariable("foo");
97
+ * });
98
+ *
99
+ * const runnable = RunnableLambda.from(async () => {
100
+ * // Set a context variable named "foo"
101
+ * setContextVariable("foo", "bar");
102
+ *
103
+ * const res = await nested.invoke({});
104
+ *
105
+ * // Still "bar" since child changes do not affect parents
106
+ * console.log(getContextVariable("foo"));
107
+ *
108
+ * return res;
109
+ * });
110
+ *
111
+ * // undefined, because context variable has not been set yet
112
+ * console.log(getContextVariable("foo"));
113
+ *
114
+ * // Final return value is "baz"
115
+ * const result = await runnable.invoke({});
116
+ * ```
117
+ *
118
+ * @param name The name of the context variable.
119
+ */
120
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
121
+ export function getContextVariable(name) {
122
+ // Avoid using global singleton due to circuluar dependency issues
123
+ const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();
124
+ if (asyncLocalStorageInstance === undefined) {
125
+ return undefined;
126
+ }
127
+ const runTree = asyncLocalStorageInstance.getStore();
128
+ return runTree?.[_CONTEXT_VARIABLES_KEY]?.[name];
129
+ }
130
+ const LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks");
131
+ export const _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || [];
132
+ /**
133
+ * Register a callback configure hook to automatically add callback handlers to all runs.
134
+ *
135
+ * There are two ways to use this:
136
+ *
137
+ * 1. Using a context variable:
138
+ * - Set `contextVar` to specify the variable name
139
+ * - Use `setContextVariable()` to store your handler instance
140
+ *
141
+ * 2. Using an environment variable:
142
+ * - Set both `envVar` and `handlerClass`
143
+ * - The handler will be instantiated when the env var is set to "true".
144
+ *
145
+ * @example
146
+ * ```typescript
147
+ * // Method 1: Using context variable
148
+ * import {
149
+ * registerConfigureHook,
150
+ * setContextVariable
151
+ * } from "@langchain/core/context";
152
+ *
153
+ * const tracer = new MyCallbackHandler();
154
+ * registerConfigureHook({
155
+ * contextVar: "my_tracer",
156
+ * });
157
+ * setContextVariable("my_tracer", tracer);
158
+ *
159
+ * // ...run code here
160
+ *
161
+ * // Method 2: Using environment variable
162
+ * registerConfigureHook({
163
+ * handlerClass: MyCallbackHandler,
164
+ * envVar: "MY_TRACER_ENABLED",
165
+ * });
166
+ * process.env.MY_TRACER_ENABLED = "true";
167
+ *
168
+ * // ...run code here
169
+ * ```
170
+ *
171
+ * @param config Configuration object for the hook
172
+ * @param config.contextVar Name of the context variable containing the handler instance
173
+ * @param config.inheritable Whether child runs should inherit this handler
174
+ * @param config.handlerClass Optional callback handler class (required if using envVar)
175
+ * @param config.envVar Optional environment variable name to control handler activation
176
+ */
177
+ export const registerConfigureHook = (config) => {
178
+ if (config.envVar && !config.handlerClass) {
179
+ throw new Error("If envVar is set, handlerClass must also be set to a non-None value.");
180
+ }
181
+ setContextVariable(LC_CONFIGURE_HOOKS_KEY, [..._getConfigureHooks(), config]);
182
+ };
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getGlobalAsyncLocalStorageInstance = exports.setGlobalAsyncLocalStorageInstance = exports.TRACING_ALS_KEY = void 0;
3
+ exports.getGlobalAsyncLocalStorageInstance = exports.setGlobalAsyncLocalStorageInstance = exports._CONTEXT_VARIABLES_KEY = exports.TRACING_ALS_KEY = void 0;
4
4
  exports.TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage");
5
+ exports._CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables");
5
6
  const setGlobalAsyncLocalStorageInstance = (instance) => {
6
7
  globalThis[exports.TRACING_ALS_KEY] = instance;
7
8
  };
@@ -4,5 +4,6 @@ export interface AsyncLocalStorageInterface {
4
4
  enterWith: (store: any) => void;
5
5
  }
6
6
  export declare const TRACING_ALS_KEY: unique symbol;
7
+ export declare const _CONTEXT_VARIABLES_KEY: unique symbol;
7
8
  export declare const setGlobalAsyncLocalStorageInstance: (instance: AsyncLocalStorageInterface) => void;
8
- export declare const getGlobalAsyncLocalStorageInstance: () => any;
9
+ export declare const getGlobalAsyncLocalStorageInstance: () => AsyncLocalStorageInterface | undefined;
@@ -1,4 +1,5 @@
1
1
  export const TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage");
2
+ export const _CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables");
2
3
  export const setGlobalAsyncLocalStorageInstance = (instance) => {
3
4
  globalThis[TRACING_ALS_KEY] = instance;
4
5
  };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AsyncLocalStorageProviderSingleton = exports._CONTEXT_VARIABLES_KEY = exports.MockAsyncLocalStorage = void 0;
3
+ exports.AsyncLocalStorageProviderSingleton = exports.MockAsyncLocalStorage = void 0;
4
4
  /* eslint-disable @typescript-eslint/no-explicit-any */
5
5
  const langsmith_1 = require("langsmith");
6
6
  const globals_js_1 = require("./globals.cjs");
@@ -19,7 +19,6 @@ class MockAsyncLocalStorage {
19
19
  exports.MockAsyncLocalStorage = MockAsyncLocalStorage;
20
20
  const mockAsyncLocalStorage = new MockAsyncLocalStorage();
21
21
  const LC_CHILD_KEY = Symbol.for("lc:child_config");
22
- exports._CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables");
23
22
  class AsyncLocalStorageProvider {
24
23
  getInstance() {
25
24
  return (0, globals_js_1.getGlobalAsyncLocalStorageInstance)() ?? mockAsyncLocalStorage;
@@ -51,9 +50,9 @@ class AsyncLocalStorageProvider {
51
50
  runTree.extra = { ...runTree.extra, [LC_CHILD_KEY]: config };
52
51
  }
53
52
  if (previousValue !== undefined &&
54
- previousValue[exports._CONTEXT_VARIABLES_KEY] !== undefined) {
55
- runTree[exports._CONTEXT_VARIABLES_KEY] =
56
- previousValue[exports._CONTEXT_VARIABLES_KEY];
53
+ previousValue[globals_js_1._CONTEXT_VARIABLES_KEY] !== undefined) {
54
+ runTree[globals_js_1._CONTEXT_VARIABLES_KEY] =
55
+ previousValue[globals_js_1._CONTEXT_VARIABLES_KEY];
57
56
  }
58
57
  return storage.run(runTree, callback);
59
58
  }
@@ -4,7 +4,6 @@ export declare class MockAsyncLocalStorage implements AsyncLocalStorageInterface
4
4
  run<T>(_store: any, callback: () => T): T;
5
5
  enterWith(_store: any): undefined;
6
6
  }
7
- export declare const _CONTEXT_VARIABLES_KEY: unique symbol;
8
7
  declare class AsyncLocalStorageProvider {
9
8
  getInstance(): AsyncLocalStorageInterface;
10
9
  getRunnableConfig(): any;
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
2
  import { RunTree } from "langsmith";
3
- import { getGlobalAsyncLocalStorageInstance, setGlobalAsyncLocalStorageInstance, } from "./globals.js";
3
+ import { getGlobalAsyncLocalStorageInstance, setGlobalAsyncLocalStorageInstance, _CONTEXT_VARIABLES_KEY, } from "./globals.js";
4
4
  import { CallbackManager } from "../../callbacks/manager.js";
5
5
  export class MockAsyncLocalStorage {
6
6
  getStore() {
@@ -15,7 +15,6 @@ export class MockAsyncLocalStorage {
15
15
  }
16
16
  const mockAsyncLocalStorage = new MockAsyncLocalStorage();
17
17
  const LC_CHILD_KEY = Symbol.for("lc:child_config");
18
- export const _CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables");
19
18
  class AsyncLocalStorageProvider {
20
19
  getInstance() {
21
20
  return getGlobalAsyncLocalStorageInstance() ?? mockAsyncLocalStorage;
@@ -36,8 +36,9 @@ async function consumeCallback(promiseFn, wait) {
36
36
  if (wait === true) {
37
37
  // Clear config since callbacks are not part of the root run
38
38
  // Avoid using global singleton due to circuluar dependency issues
39
- if ((0, globals_js_1.getGlobalAsyncLocalStorageInstance)() !== undefined) {
40
- await (0, globals_js_1.getGlobalAsyncLocalStorageInstance)().run(undefined, async () => promiseFn());
39
+ const asyncLocalStorageInstance = (0, globals_js_1.getGlobalAsyncLocalStorageInstance)();
40
+ if (asyncLocalStorageInstance !== undefined) {
41
+ await asyncLocalStorageInstance.run(undefined, async () => promiseFn());
41
42
  }
42
43
  else {
43
44
  await promiseFn();
@@ -46,8 +47,9 @@ async function consumeCallback(promiseFn, wait) {
46
47
  else {
47
48
  queue = getQueue();
48
49
  void queue.add(async () => {
49
- if ((0, globals_js_1.getGlobalAsyncLocalStorageInstance)() !== undefined) {
50
- await (0, globals_js_1.getGlobalAsyncLocalStorageInstance)().run(undefined, async () => promiseFn());
50
+ const asyncLocalStorageInstance = (0, globals_js_1.getGlobalAsyncLocalStorageInstance)();
51
+ if (asyncLocalStorageInstance !== undefined) {
52
+ await asyncLocalStorageInstance.run(undefined, async () => promiseFn());
51
53
  }
52
54
  else {
53
55
  await promiseFn();
@@ -29,8 +29,9 @@ export async function consumeCallback(promiseFn, wait) {
29
29
  if (wait === true) {
30
30
  // Clear config since callbacks are not part of the root run
31
31
  // Avoid using global singleton due to circuluar dependency issues
32
- if (getGlobalAsyncLocalStorageInstance() !== undefined) {
33
- await getGlobalAsyncLocalStorageInstance().run(undefined, async () => promiseFn());
32
+ const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();
33
+ if (asyncLocalStorageInstance !== undefined) {
34
+ await asyncLocalStorageInstance.run(undefined, async () => promiseFn());
34
35
  }
35
36
  else {
36
37
  await promiseFn();
@@ -39,8 +40,9 @@ export async function consumeCallback(promiseFn, wait) {
39
40
  else {
40
41
  queue = getQueue();
41
42
  void queue.add(async () => {
42
- if (getGlobalAsyncLocalStorageInstance() !== undefined) {
43
- await getGlobalAsyncLocalStorageInstance().run(undefined, async () => promiseFn());
43
+ const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();
44
+ if (asyncLocalStorageInstance !== undefined) {
45
+ await asyncLocalStorageInstance.run(undefined, async () => promiseFn());
44
46
  }
45
47
  else {
46
48
  await promiseFn();
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MockAsyncLocalStorage = exports._CONTEXT_VARIABLES_KEY = exports.AsyncLocalStorageProviderSingleton = void 0;
4
- /* eslint-disable @typescript-eslint/no-explicit-any */
3
+ exports._CONTEXT_VARIABLES_KEY = exports.MockAsyncLocalStorage = exports.AsyncLocalStorageProviderSingleton = void 0;
5
4
  const index_js_1 = require("./async_local_storage/index.cjs");
6
5
  Object.defineProperty(exports, "AsyncLocalStorageProviderSingleton", { enumerable: true, get: function () { return index_js_1.AsyncLocalStorageProviderSingleton; } });
7
- Object.defineProperty(exports, "_CONTEXT_VARIABLES_KEY", { enumerable: true, get: function () { return index_js_1._CONTEXT_VARIABLES_KEY; } });
8
6
  Object.defineProperty(exports, "MockAsyncLocalStorage", { enumerable: true, get: function () { return index_js_1.MockAsyncLocalStorage; } });
7
+ const globals_js_1 = require("./async_local_storage/globals.cjs");
8
+ Object.defineProperty(exports, "_CONTEXT_VARIABLES_KEY", { enumerable: true, get: function () { return globals_js_1._CONTEXT_VARIABLES_KEY; } });
@@ -1,2 +1,4 @@
1
- import { type AsyncLocalStorageInterface, AsyncLocalStorageProviderSingleton, _CONTEXT_VARIABLES_KEY, MockAsyncLocalStorage } from "./async_local_storage/index.js";
2
- export { type AsyncLocalStorageInterface, AsyncLocalStorageProviderSingleton, _CONTEXT_VARIABLES_KEY, MockAsyncLocalStorage, };
1
+ import { type AsyncLocalStorageInterface, AsyncLocalStorageProviderSingleton, MockAsyncLocalStorage } from "./async_local_storage/index.js";
2
+ import { _CONTEXT_VARIABLES_KEY } from "./async_local_storage/globals.js";
3
+ export { type AsyncLocalStorageInterface, AsyncLocalStorageProviderSingleton, MockAsyncLocalStorage, };
4
+ export { _CONTEXT_VARIABLES_KEY };
@@ -1,3 +1,4 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
- import { AsyncLocalStorageProviderSingleton, _CONTEXT_VARIABLES_KEY, MockAsyncLocalStorage, } from "./async_local_storage/index.js";
3
- export { AsyncLocalStorageProviderSingleton, _CONTEXT_VARIABLES_KEY, MockAsyncLocalStorage, };
1
+ import { AsyncLocalStorageProviderSingleton, MockAsyncLocalStorage, } from "./async_local_storage/index.js";
2
+ import { _CONTEXT_VARIABLES_KEY } from "./async_local_storage/globals.js";
3
+ export { AsyncLocalStorageProviderSingleton, MockAsyncLocalStorage, };
4
+ export { _CONTEXT_VARIABLES_KEY };
@@ -60,21 +60,23 @@ class StructuredTool extends base_js_1.BaseLangChain {
60
60
  async invoke(input, config) {
61
61
  let tool_call_id;
62
62
  let toolInput;
63
+ let enrichedConfig = (0, config_js_1.ensureConfig)(config);
63
64
  if ((0, utils_js_1._isToolCall)(input)) {
64
65
  tool_call_id = input.id;
65
66
  toolInput = input.args;
67
+ enrichedConfig = {
68
+ ...enrichedConfig,
69
+ toolCall: input,
70
+ configurable: {
71
+ ...enrichedConfig.configurable,
72
+ tool_call_id,
73
+ },
74
+ };
66
75
  }
67
76
  else {
68
77
  toolInput = input;
69
78
  }
70
- const ensuredConfig = (0, config_js_1.ensureConfig)(config);
71
- return this.call(toolInput, {
72
- ...ensuredConfig,
73
- configurable: {
74
- ...ensuredConfig.configurable,
75
- tool_call_id,
76
- },
77
- });
79
+ return this.call(toolInput, enrichedConfig);
78
80
  }
79
81
  /**
80
82
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
@@ -103,7 +105,7 @@ class StructuredTool extends base_js_1.BaseLangChain {
103
105
  throw new utils_js_1.ToolInputParsingException(message, JSON.stringify(arg));
104
106
  }
105
107
  const config = (0, manager_js_1.parseCallbackConfigArg)(configArg);
106
- const callbackManager_ = await manager_js_1.CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose });
108
+ const callbackManager_ = manager_js_1.CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose });
107
109
  const runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof parsed === "string" ? parsed : JSON.stringify(parsed), config.runId, undefined, undefined, undefined, config.runName);
108
110
  delete config.runId;
109
111
  let result;
@@ -310,7 +312,7 @@ function tool(func, fields) {
310
312
  const childConfig = (0, config_js_1.patchConfig)(config, {
311
313
  callbacks: runManager?.getChild(),
312
314
  });
313
- void index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {
315
+ void index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig((0, config_js_1.pickRunnableConfigKeys)(childConfig), async () => {
314
316
  try {
315
317
  // TS doesn't restrict the type here based on the guard above
316
318
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -336,7 +338,7 @@ function tool(func, fields) {
336
338
  const childConfig = (0, config_js_1.patchConfig)(config, {
337
339
  callbacks: runManager?.getChild(),
338
340
  });
339
- void index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {
341
+ void index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig((0, config_js_1.pickRunnableConfigKeys)(childConfig), async () => {
340
342
  try {
341
343
  // TS doesn't restrict the type here based on the guard above
342
344
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -353,7 +355,7 @@ function tool(func, fields) {
353
355
  exports.tool = tool;
354
356
  function _formatToolOutput(params) {
355
357
  const { content, artifact, toolCallId } = params;
356
- if (toolCallId) {
358
+ if (toolCallId && !(0, tool_js_1.isDirectToolOutput)(content)) {
357
359
  if (typeof content === "string" ||
358
360
  (Array.isArray(content) &&
359
361
  content.every((item) => typeof item === "object"))) {
@@ -32,6 +32,9 @@ export interface ToolParams extends BaseLangChainParams {
32
32
  */
33
33
  verboseParsingErrors?: boolean;
34
34
  }
35
+ export type ToolRunnableConfig<ConfigurableFieldType extends Record<string, any> = Record<string, any>> = RunnableConfig<ConfigurableFieldType> & {
36
+ toolCall?: ToolCall;
37
+ };
35
38
  /**
36
39
  * Schema for defining tools.
37
40
  *
@@ -94,7 +97,7 @@ export declare abstract class StructuredTool<T extends ZodObjectAny = ZodObjectA
94
97
  */
95
98
  responseFormat?: ResponseFormat;
96
99
  constructor(fields?: ToolParams);
97
- protected abstract _call(arg: z.output<T>, runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolReturnType>;
100
+ protected abstract _call(arg: z.output<T>, runManager?: CallbackManagerForToolRun, parentConfig?: ToolRunnableConfig): Promise<ToolReturnType>;
98
101
  /**
99
102
  * Invokes the tool with the provided input and configuration.
100
103
  * @param input The input for the tool.
@@ -113,7 +116,7 @@ export declare abstract class StructuredTool<T extends ZodObjectAny = ZodObjectA
113
116
  * @param tags Optional tags for the tool.
114
117
  * @returns A Promise that resolves with a string.
115
118
  */
116
- call(arg: (z.output<T> extends string ? string : never) | z.input<T> | ToolCall, configArg?: Callbacks | RunnableConfig,
119
+ call(arg: (z.output<T> extends string ? string : never) | z.input<T>, configArg?: Callbacks | ToolRunnableConfig,
117
120
  /** @deprecated */
118
121
  tags?: string[]): Promise<ToolReturnType>;
119
122
  }
@@ -163,7 +166,7 @@ export interface BaseDynamicToolInput extends ToolParams {
163
166
  * Interface for the input parameters of the DynamicTool class.
164
167
  */
165
168
  export interface DynamicToolInput extends BaseDynamicToolInput {
166
- func: (input: string, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolReturnType>;
169
+ func: (input: string, runManager?: CallbackManagerForToolRun, config?: ToolRunnableConfig) => Promise<ToolReturnType>;
167
170
  }
168
171
  /**
169
172
  * Interface for the input parameters of the DynamicStructuredTool class.
@@ -184,9 +187,9 @@ export declare class DynamicTool extends Tool {
184
187
  /**
185
188
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
186
189
  */
187
- call(arg: string | undefined | z.input<this["schema"]> | ToolCall, configArg?: RunnableConfig | Callbacks): Promise<ToolReturnType>;
190
+ call(arg: string | undefined | z.input<this["schema"]> | ToolCall, configArg?: ToolRunnableConfig | Callbacks): Promise<ToolReturnType>;
188
191
  /** @ignore */
189
- _call(input: string, runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolReturnType>;
192
+ _call(input: string, runManager?: CallbackManagerForToolRun, parentConfig?: ToolRunnableConfig): Promise<ToolReturnType>;
190
193
  }
191
194
  /**
192
195
  * A tool that can be created dynamically from a function, name, and
@@ -272,6 +275,6 @@ interface ToolWrapperParams<RunInput extends ZodObjectAny | z.ZodString | Record
272
275
  *
273
276
  * @returns {DynamicStructuredTool<T>} A new StructuredTool instance.
274
277
  */
275
- export declare function tool<T extends z.ZodString>(func: RunnableFunc<z.output<T>, ToolReturnType>, fields: ToolWrapperParams<T>): DynamicTool;
276
- export declare function tool<T extends ZodObjectAny>(func: RunnableFunc<z.output<T>, ToolReturnType>, fields: ToolWrapperParams<T>): DynamicStructuredTool<T>;
277
- export declare function tool<T extends Record<string, any>>(func: RunnableFunc<T, ToolReturnType>, fields: ToolWrapperParams<T>): DynamicStructuredTool<T>;
278
+ export declare function tool<T extends z.ZodString>(func: RunnableFunc<z.output<T>, ToolReturnType, ToolRunnableConfig>, fields: ToolWrapperParams<T>): DynamicTool;
279
+ export declare function tool<T extends ZodObjectAny>(func: RunnableFunc<z.output<T>, ToolReturnType, ToolRunnableConfig>, fields: ToolWrapperParams<T>): DynamicStructuredTool<T>;
280
+ export declare function tool<T extends Record<string, any>>(func: RunnableFunc<T, ToolReturnType, ToolRunnableConfig>, fields: ToolWrapperParams<T>): DynamicStructuredTool<T>;
@@ -1,8 +1,8 @@
1
1
  import { z } from "zod";
2
2
  import { CallbackManager, parseCallbackConfigArg, } from "../callbacks/manager.js";
3
3
  import { BaseLangChain, } from "../language_models/base.js";
4
- import { ensureConfig, patchConfig, } from "../runnables/config.js";
5
- import { ToolMessage } from "../messages/tool.js";
4
+ import { ensureConfig, patchConfig, pickRunnableConfigKeys, } from "../runnables/config.js";
5
+ import { isDirectToolOutput, ToolMessage } from "../messages/tool.js";
6
6
  import { AsyncLocalStorageProviderSingleton } from "../singletons/index.js";
7
7
  import { _isToolCall, ToolInputParsingException } from "./utils.js";
8
8
  import { isZodSchema } from "../utils/types/is_zod_schema.js";
@@ -57,21 +57,23 @@ export class StructuredTool extends BaseLangChain {
57
57
  async invoke(input, config) {
58
58
  let tool_call_id;
59
59
  let toolInput;
60
+ let enrichedConfig = ensureConfig(config);
60
61
  if (_isToolCall(input)) {
61
62
  tool_call_id = input.id;
62
63
  toolInput = input.args;
64
+ enrichedConfig = {
65
+ ...enrichedConfig,
66
+ toolCall: input,
67
+ configurable: {
68
+ ...enrichedConfig.configurable,
69
+ tool_call_id,
70
+ },
71
+ };
63
72
  }
64
73
  else {
65
74
  toolInput = input;
66
75
  }
67
- const ensuredConfig = ensureConfig(config);
68
- return this.call(toolInput, {
69
- ...ensuredConfig,
70
- configurable: {
71
- ...ensuredConfig.configurable,
72
- tool_call_id,
73
- },
74
- });
76
+ return this.call(toolInput, enrichedConfig);
75
77
  }
76
78
  /**
77
79
  * @deprecated Use .invoke() instead. Will be removed in 0.3.0.
@@ -100,7 +102,7 @@ export class StructuredTool extends BaseLangChain {
100
102
  throw new ToolInputParsingException(message, JSON.stringify(arg));
101
103
  }
102
104
  const config = parseCallbackConfigArg(configArg);
103
- const callbackManager_ = await CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose });
105
+ const callbackManager_ = CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose });
104
106
  const runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof parsed === "string" ? parsed : JSON.stringify(parsed), config.runId, undefined, undefined, undefined, config.runName);
105
107
  delete config.runId;
106
108
  let result;
@@ -302,7 +304,7 @@ export function tool(func, fields) {
302
304
  const childConfig = patchConfig(config, {
303
305
  callbacks: runManager?.getChild(),
304
306
  });
305
- void AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {
307
+ void AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {
306
308
  try {
307
309
  // TS doesn't restrict the type here based on the guard above
308
310
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -328,7 +330,7 @@ export function tool(func, fields) {
328
330
  const childConfig = patchConfig(config, {
329
331
  callbacks: runManager?.getChild(),
330
332
  });
331
- void AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => {
333
+ void AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => {
332
334
  try {
333
335
  // TS doesn't restrict the type here based on the guard above
334
336
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -344,7 +346,7 @@ export function tool(func, fields) {
344
346
  }
345
347
  function _formatToolOutput(params) {
346
348
  const { content, artifact, toolCallId } = params;
347
- if (toolCallId) {
349
+ if (toolCallId && !isDirectToolOutput(content)) {
348
350
  if (typeof content === "string" ||
349
351
  (Array.isArray(content) &&
350
352
  content.every((item) => typeof item === "object"))) {
@@ -0,0 +1 @@
1
+ export type IterableReadableStreamInterface<T> = ReadableStream<T> & AsyncIterable<T>;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Validator = exports.deepCompareStrict = void 0;
4
- var index_js_1 = require("./@cfworker/json-schema/index.cjs");
5
- Object.defineProperty(exports, "deepCompareStrict", { enumerable: true, get: function () { return index_js_1.deepCompareStrict; } });
6
- Object.defineProperty(exports, "Validator", { enumerable: true, get: function () { return index_js_1.Validator; } });
4
+ var json_schema_1 = require("@cfworker/json-schema");
5
+ Object.defineProperty(exports, "deepCompareStrict", { enumerable: true, get: function () { return json_schema_1.deepCompareStrict; } });
6
+ Object.defineProperty(exports, "Validator", { enumerable: true, get: function () { return json_schema_1.Validator; } });
@@ -1 +1 @@
1
- export { deepCompareStrict, Validator } from "./@cfworker/json-schema/index.js";
1
+ export { deepCompareStrict, Validator } from "@cfworker/json-schema";
@@ -1 +1 @@
1
- export { deepCompareStrict, Validator } from "./@cfworker/json-schema/index.js";
1
+ export { deepCompareStrict, Validator } from "@cfworker/json-schema";
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.pipeGeneratorWithSetup = exports.AsyncGeneratorWithSetup = exports.concat = exports.atee = exports.IterableReadableStream = void 0;
4
+ const config_js_1 = require("../runnables/config.cjs");
4
5
  const index_js_1 = require("../singletons/index.cjs");
5
6
  const signal_js_1 = require("./signal.cjs");
6
7
  /*
@@ -220,7 +221,7 @@ class AsyncGeneratorWithSetup {
220
221
  // needs to happen in logical order, ie. in the order in which input to
221
222
  // to each generator is available.
222
223
  this.setup = new Promise((resolve, reject) => {
223
- void index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig(params.config, async () => {
224
+ void index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig((0, config_js_1.pickRunnableConfigKeys)(params.config), async () => {
224
225
  this.firstResult = params.generator.next();
225
226
  if (params.startSetup) {
226
227
  this.firstResult.then(params.startSetup).then(resolve, reject);
@@ -237,7 +238,7 @@ class AsyncGeneratorWithSetup {
237
238
  this.firstResultUsed = true;
238
239
  return this.firstResult;
239
240
  }
240
- return index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig(this.config, this.signal
241
+ return index_js_1.AsyncLocalStorageProviderSingleton.runWithConfig((0, config_js_1.pickRunnableConfigKeys)(this.config), this.signal
241
242
  ? async () => {
242
243
  return (0, signal_js_1.raceWithSignal)(this.generator.next(...args), this.signal);
243
244
  }
@@ -1,4 +1,5 @@
1
- export type IterableReadableStreamInterface<T> = ReadableStream<T> & AsyncIterable<T>;
1
+ import type { IterableReadableStreamInterface } from "../types/stream.js";
2
+ export type { IterableReadableStreamInterface };
2
3
  export declare class IterableReadableStream<T> extends ReadableStream<T> implements IterableReadableStreamInterface<T> {
3
4
  reader: ReadableStreamDefaultReader<T>;
4
5
  ensureReader(): void;
@@ -1,3 +1,4 @@
1
+ import { pickRunnableConfigKeys } from "../runnables/config.js";
1
2
  import { AsyncLocalStorageProviderSingleton } from "../singletons/index.js";
2
3
  import { raceWithSignal } from "./signal.js";
3
4
  /*
@@ -214,7 +215,7 @@ export class AsyncGeneratorWithSetup {
214
215
  // needs to happen in logical order, ie. in the order in which input to
215
216
  // to each generator is available.
216
217
  this.setup = new Promise((resolve, reject) => {
217
- void AsyncLocalStorageProviderSingleton.runWithConfig(params.config, async () => {
218
+ void AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(params.config), async () => {
218
219
  this.firstResult = params.generator.next();
219
220
  if (params.startSetup) {
220
221
  this.firstResult.then(params.startSetup).then(resolve, reject);
@@ -231,7 +232,7 @@ export class AsyncGeneratorWithSetup {
231
232
  this.firstResultUsed = true;
232
233
  return this.firstResult;
233
234
  }
234
- return AsyncLocalStorageProviderSingleton.runWithConfig(this.config, this.signal
235
+ return AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(this.config), this.signal
235
236
  ? async () => {
236
237
  return raceWithSignal(this.generator.next(...args), this.signal);
237
238
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/core",
3
- "version": "0.3.21",
3
+ "version": "0.3.23",
4
4
  "description": "Core LangChain.js abstractions and schemas",
5
5
  "type": "module",
6
6
  "engines": {
@@ -33,6 +33,7 @@
33
33
  "author": "LangChain",
34
34
  "license": "MIT",
35
35
  "dependencies": {
36
+ "@cfworker/json-schema": "^4.0.2",
36
37
  "ansi-styles": "^5.0.0",
37
38
  "camelcase": "6",
38
39
  "decamelize": "1.2.0",