langchain 0.0.195 → 0.0.197-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.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/dist/agents/openai/index.cjs +6 -2
  3. package/dist/agents/openai/index.js +6 -2
  4. package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.d.ts +1 -1
  5. package/dist/base_language/count_tokens.cjs +5 -70
  6. package/dist/base_language/count_tokens.d.ts +1 -10
  7. package/dist/base_language/count_tokens.js +1 -65
  8. package/dist/base_language/index.cjs +6 -196
  9. package/dist/base_language/index.d.ts +1 -111
  10. package/dist/base_language/index.js +1 -191
  11. package/dist/cache/base.cjs +15 -37
  12. package/dist/cache/base.d.ts +1 -20
  13. package/dist/cache/base.js +1 -33
  14. package/dist/cache/index.cjs +2 -46
  15. package/dist/cache/index.d.ts +1 -29
  16. package/dist/cache/index.js +1 -45
  17. package/dist/callbacks/base.cjs +3 -139
  18. package/dist/callbacks/base.d.ts +1 -266
  19. package/dist/callbacks/base.js +1 -126
  20. package/dist/callbacks/handlers/console.cjs +14 -221
  21. package/dist/callbacks/handlers/console.d.ts +1 -117
  22. package/dist/callbacks/handlers/console.js +1 -217
  23. package/dist/callbacks/handlers/initialize.cjs +15 -30
  24. package/dist/callbacks/handlers/initialize.d.ts +1 -16
  25. package/dist/callbacks/handlers/initialize.js +1 -27
  26. package/dist/callbacks/handlers/log_stream.cjs +15 -293
  27. package/dist/callbacks/handlers/log_stream.d.ts +1 -100
  28. package/dist/callbacks/handlers/log_stream.js +1 -289
  29. package/dist/callbacks/handlers/run_collector.cjs +15 -48
  30. package/dist/callbacks/handlers/run_collector.d.ts +1 -26
  31. package/dist/callbacks/handlers/run_collector.js +1 -46
  32. package/dist/callbacks/handlers/tracer.cjs +15 -375
  33. package/dist/callbacks/handlers/tracer.d.ts +1 -70
  34. package/dist/callbacks/handlers/tracer.js +1 -373
  35. package/dist/callbacks/handlers/tracer_langchain.cjs +15 -104
  36. package/dist/callbacks/handlers/tracer_langchain.d.ts +1 -41
  37. package/dist/callbacks/handlers/tracer_langchain.js +1 -102
  38. package/dist/callbacks/handlers/tracer_langchain_v1.cjs +15 -197
  39. package/dist/callbacks/handlers/tracer_langchain_v1.d.ts +1 -57
  40. package/dist/callbacks/handlers/tracer_langchain_v1.js +1 -195
  41. package/dist/callbacks/manager.cjs +15 -676
  42. package/dist/callbacks/manager.d.ts +1 -180
  43. package/dist/callbacks/manager.js +1 -666
  44. package/dist/callbacks/promises.cjs +14 -42
  45. package/dist/callbacks/promises.d.ts +1 -11
  46. package/dist/callbacks/promises.js +1 -37
  47. package/dist/chains/graph_qa/prompts.d.ts +1 -1
  48. package/dist/chains/openai_functions/structured_output.cjs +2 -2
  49. package/dist/chains/openai_functions/structured_output.d.ts +1 -1
  50. package/dist/chains/openai_functions/structured_output.js +1 -1
  51. package/dist/chat_models/anthropic.cjs +15 -348
  52. package/dist/chat_models/anthropic.d.ts +1 -156
  53. package/dist/chat_models/anthropic.js +1 -346
  54. package/dist/chat_models/baiduwenxin.d.ts +1 -1
  55. package/dist/chat_models/base.cjs +15 -296
  56. package/dist/chat_models/base.d.ts +1 -122
  57. package/dist/chat_models/base.js +1 -292
  58. package/dist/chat_models/bedrock/web.cjs +21 -1
  59. package/dist/chat_models/bedrock/web.d.ts +2 -2
  60. package/dist/chat_models/bedrock/web.js +21 -1
  61. package/dist/chat_models/fireworks.d.ts +1 -1
  62. package/dist/document.cjs +2 -24
  63. package/dist/document.d.ts +1 -12
  64. package/dist/document.js +1 -23
  65. package/dist/document_loaders/web/azure_blob_storage_file.d.ts +1 -1
  66. package/dist/document_loaders/web/github.cjs +105 -0
  67. package/dist/document_loaders/web/github.d.ts +26 -0
  68. package/dist/document_loaders/web/github.js +105 -0
  69. package/dist/document_loaders/web/s3.d.ts +1 -1
  70. package/dist/embeddings/base.cjs +15 -22
  71. package/dist/embeddings/base.d.ts +1 -33
  72. package/dist/embeddings/base.js +1 -20
  73. package/dist/embeddings/cache_backed.cjs +2 -2
  74. package/dist/embeddings/cache_backed.js +1 -1
  75. package/dist/evaluation/agents/trajectory.d.ts +1 -1
  76. package/dist/evaluation/criteria/prompt.d.ts +2 -2
  77. package/dist/evaluation/qa/prompt.d.ts +2 -2
  78. package/dist/experimental/hubs/makersuite/googlemakersuitehub.d.ts +1 -1
  79. package/dist/experimental/plan_and_execute/prompt.d.ts +1 -1
  80. package/dist/llms/base.cjs +15 -278
  81. package/dist/llms/base.d.ts +1 -115
  82. package/dist/llms/base.js +1 -275
  83. package/dist/llms/bedrock/web.cjs +21 -1
  84. package/dist/llms/bedrock/web.d.ts +2 -2
  85. package/dist/llms/bedrock/web.js +21 -1
  86. package/dist/llms/fireworks.d.ts +1 -1
  87. package/dist/load/import_map.cjs +2 -1
  88. package/dist/load/import_map.d.ts +1 -0
  89. package/dist/load/import_map.js +1 -0
  90. package/dist/load/index.cjs +7 -148
  91. package/dist/load/index.js +7 -148
  92. package/dist/load/map_keys.cjs +0 -24
  93. package/dist/load/map_keys.d.ts +0 -6
  94. package/dist/load/map_keys.js +1 -17
  95. package/dist/load/serializable.cjs +15 -178
  96. package/dist/load/serializable.d.ts +1 -66
  97. package/dist/load/serializable.js +1 -175
  98. package/dist/memory/base.cjs +17 -92
  99. package/dist/memory/base.d.ts +2 -68
  100. package/dist/memory/base.js +2 -87
  101. package/dist/output_parsers/list.cjs +4 -122
  102. package/dist/output_parsers/list.d.ts +1 -57
  103. package/dist/output_parsers/list.js +1 -119
  104. package/dist/output_parsers/openai_functions.cjs +2 -2
  105. package/dist/output_parsers/openai_functions.d.ts +1 -1
  106. package/dist/output_parsers/openai_functions.js +1 -1
  107. package/dist/output_parsers/regex.d.ts +1 -1
  108. package/dist/output_parsers/structured.d.ts +1 -1
  109. package/dist/prompts/base.cjs +8 -183
  110. package/dist/prompts/base.d.ts +3 -132
  111. package/dist/prompts/base.js +3 -178
  112. package/dist/prompts/chat.cjs +13 -477
  113. package/dist/prompts/chat.d.ts +2 -219
  114. package/dist/prompts/chat.js +2 -466
  115. package/dist/prompts/few_shot.cjs +3 -352
  116. package/dist/prompts/few_shot.d.ts +1 -192
  117. package/dist/prompts/few_shot.js +1 -350
  118. package/dist/prompts/index.cjs +3 -2
  119. package/dist/prompts/index.d.ts +2 -1
  120. package/dist/prompts/index.js +2 -1
  121. package/dist/prompts/pipeline.cjs +2 -141
  122. package/dist/prompts/pipeline.d.ts +1 -98
  123. package/dist/prompts/pipeline.js +1 -140
  124. package/dist/prompts/prompt.cjs +2 -145
  125. package/dist/prompts/prompt.d.ts +1 -92
  126. package/dist/prompts/prompt.js +1 -144
  127. package/dist/prompts/selectors/LengthBasedExampleSelector.cjs +2 -147
  128. package/dist/prompts/selectors/LengthBasedExampleSelector.d.ts +1 -89
  129. package/dist/prompts/selectors/LengthBasedExampleSelector.js +1 -146
  130. package/dist/prompts/selectors/SemanticSimilarityExampleSelector.cjs +15 -137
  131. package/dist/prompts/selectors/SemanticSimilarityExampleSelector.d.ts +1 -91
  132. package/dist/prompts/selectors/SemanticSimilarityExampleSelector.js +1 -135
  133. package/dist/prompts/selectors/conditional.cjs +5 -73
  134. package/dist/prompts/selectors/conditional.d.ts +1 -63
  135. package/dist/prompts/selectors/conditional.js +1 -69
  136. package/dist/prompts/serde.d.ts +1 -43
  137. package/dist/prompts/template.cjs +8 -88
  138. package/dist/prompts/template.d.ts +1 -36
  139. package/dist/prompts/template.js +1 -83
  140. package/dist/{util/@cfworker/json-schema → runnables}/index.cjs +1 -1
  141. package/dist/runnables/index.d.ts +1 -0
  142. package/dist/runnables/index.js +1 -0
  143. package/dist/schema/document.cjs +3 -34
  144. package/dist/schema/document.d.ts +2 -29
  145. package/dist/schema/document.js +2 -32
  146. package/dist/schema/index.cjs +37 -612
  147. package/dist/schema/index.d.ts +11 -311
  148. package/dist/schema/index.js +8 -583
  149. package/dist/schema/output_parser.cjs +15 -309
  150. package/dist/schema/output_parser.d.ts +1 -173
  151. package/dist/schema/output_parser.js +1 -301
  152. package/dist/schema/retriever.cjs +15 -77
  153. package/dist/schema/retriever.d.ts +1 -43
  154. package/dist/schema/retriever.js +1 -75
  155. package/dist/schema/runnable/base.cjs +10 -1072
  156. package/dist/schema/runnable/base.d.ts +1 -356
  157. package/dist/schema/runnable/base.js +1 -1060
  158. package/dist/schema/runnable/branch.cjs +2 -131
  159. package/dist/schema/runnable/branch.d.ts +1 -94
  160. package/dist/schema/runnable/branch.js +1 -130
  161. package/dist/schema/runnable/config.cjs +0 -6
  162. package/dist/schema/runnable/config.d.ts +1 -3
  163. package/dist/schema/runnable/config.js +1 -4
  164. package/dist/schema/runnable/index.cjs +15 -16
  165. package/dist/schema/runnable/index.d.ts +1 -5
  166. package/dist/schema/runnable/index.js +1 -4
  167. package/dist/schema/runnable/passthrough.cjs +3 -113
  168. package/dist/schema/runnable/passthrough.d.ts +1 -72
  169. package/dist/schema/runnable/passthrough.js +1 -111
  170. package/dist/schema/runnable/router.cjs +2 -71
  171. package/dist/schema/runnable/router.d.ts +1 -29
  172. package/dist/schema/runnable/router.js +1 -70
  173. package/dist/schema/storage.cjs +15 -8
  174. package/dist/schema/storage.d.ts +1 -57
  175. package/dist/schema/storage.js +1 -6
  176. package/dist/tools/bingserpapi.d.ts +1 -1
  177. package/dist/tools/searchapi.d.ts +1 -1
  178. package/dist/tools/serpapi.d.ts +1 -1
  179. package/dist/tools/serper.d.ts +1 -1
  180. package/dist/util/async_caller.cjs +14 -128
  181. package/dist/util/async_caller.d.ts +1 -45
  182. package/dist/util/async_caller.js +1 -124
  183. package/dist/vectorstores/momento_vector_index.cjs +39 -0
  184. package/dist/vectorstores/momento_vector_index.d.ts +17 -1
  185. package/dist/vectorstores/momento_vector_index.js +40 -1
  186. package/dist/vectorstores/mongodb_atlas.cjs +22 -2
  187. package/dist/vectorstores/mongodb_atlas.d.ts +13 -0
  188. package/dist/vectorstores/mongodb_atlas.js +22 -2
  189. package/package.json +18 -11
  190. package/runnables.cjs +1 -0
  191. package/runnables.d.ts +1 -0
  192. package/runnables.js +1 -0
  193. package/dist/util/@cfworker/json-schema/index.d.ts +0 -1
  194. package/dist/util/@cfworker/json-schema/index.js +0 -1
  195. package/dist/util/@cfworker/json-schema/src/deep-compare-strict.cjs +0 -43
  196. package/dist/util/@cfworker/json-schema/src/deep-compare-strict.d.ts +0 -1
  197. package/dist/util/@cfworker/json-schema/src/deep-compare-strict.js +0 -39
  198. package/dist/util/@cfworker/json-schema/src/dereference.cjs +0 -169
  199. package/dist/util/@cfworker/json-schema/src/dereference.d.ts +0 -12
  200. package/dist/util/@cfworker/json-schema/src/dereference.js +0 -165
  201. package/dist/util/@cfworker/json-schema/src/format.cjs +0 -139
  202. package/dist/util/@cfworker/json-schema/src/format.d.ts +0 -2
  203. package/dist/util/@cfworker/json-schema/src/format.js +0 -136
  204. package/dist/util/@cfworker/json-schema/src/index.cjs +0 -24
  205. package/dist/util/@cfworker/json-schema/src/index.d.ts +0 -8
  206. package/dist/util/@cfworker/json-schema/src/index.js +0 -8
  207. package/dist/util/@cfworker/json-schema/src/pointer.cjs +0 -11
  208. package/dist/util/@cfworker/json-schema/src/pointer.d.ts +0 -2
  209. package/dist/util/@cfworker/json-schema/src/pointer.js +0 -6
  210. package/dist/util/@cfworker/json-schema/src/types.cjs +0 -2
  211. package/dist/util/@cfworker/json-schema/src/types.d.ts +0 -72
  212. package/dist/util/@cfworker/json-schema/src/types.js +0 -1
  213. package/dist/util/@cfworker/json-schema/src/ucs2-length.cjs +0 -28
  214. package/dist/util/@cfworker/json-schema/src/ucs2-length.d.ts +0 -6
  215. package/dist/util/@cfworker/json-schema/src/ucs2-length.js +0 -24
  216. package/dist/util/@cfworker/json-schema/src/validate.cjs +0 -808
  217. package/dist/util/@cfworker/json-schema/src/validate.d.ts +0 -3
  218. package/dist/util/@cfworker/json-schema/src/validate.js +0 -804
  219. package/dist/util/@cfworker/json-schema/src/validator.cjs +0 -44
  220. package/dist/util/@cfworker/json-schema/src/validator.d.ts +0 -10
  221. package/dist/util/@cfworker/json-schema/src/validator.js +0 -40
  222. package/dist/util/fast-json-patch/index.cjs +0 -49
  223. package/dist/util/fast-json-patch/index.d.ts +0 -22
  224. package/dist/util/fast-json-patch/index.js +0 -16
  225. package/dist/util/fast-json-patch/src/core.cjs +0 -469
  226. package/dist/util/fast-json-patch/src/core.d.ts +0 -111
  227. package/dist/util/fast-json-patch/src/core.js +0 -459
  228. package/dist/util/fast-json-patch/src/duplex.cjs +0 -237
  229. package/dist/util/fast-json-patch/src/duplex.d.ts +0 -23
  230. package/dist/util/fast-json-patch/src/duplex.js +0 -230
  231. package/dist/util/fast-json-patch/src/helpers.cjs +0 -194
  232. package/dist/util/fast-json-patch/src/helpers.d.ts +0 -36
  233. package/dist/util/fast-json-patch/src/helpers.js +0 -181
  234. package/dist/util/js-sha1/hash.cjs +0 -358
  235. package/dist/util/js-sha1/hash.d.ts +0 -1
  236. package/dist/util/js-sha1/hash.js +0 -355
@@ -1,1075 +1,13 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports._coerceToRunnable = exports.RunnableWithFallbacks = exports.RunnableLambda = exports.RunnableMap = exports.RunnableSequence = exports.RunnableRetry = exports.RunnableEach = exports.RunnableBinding = exports.Runnable = void 0;
7
- const p_retry_1 = __importDefault(require("p-retry"));
8
- const manager_js_1 = require("../../callbacks/manager.cjs");
9
- const log_stream_js_1 = require("../../callbacks/handlers/log_stream.cjs");
10
- const serializable_js_1 = require("../../load/serializable.cjs");
11
- const stream_js_1 = require("../../util/stream.cjs");
12
- const config_js_1 = require("./config.cjs");
13
- const async_caller_js_1 = require("../../util/async_caller.cjs");
14
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
- function _coerceToDict(value, defaultKey) {
16
- return value && !Array.isArray(value) && typeof value === "object"
17
- ? value
18
- : { [defaultKey]: value };
19
- }
20
- /**
21
- * A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or
22
- * transformed.
23
- */
24
- class Runnable extends serializable_js_1.Serializable {
25
- constructor() {
26
- super(...arguments);
27
- Object.defineProperty(this, "lc_runnable", {
28
- enumerable: true,
29
- configurable: true,
30
- writable: true,
31
- value: true
32
- });
33
- }
34
- /**
35
- * Bind arguments to a Runnable, returning a new Runnable.
36
- * @param kwargs
37
- * @returns A new RunnableBinding that, when invoked, will apply the bound args.
38
- */
39
- bind(kwargs) {
40
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
41
- return new RunnableBinding({ bound: this, kwargs, config: {} });
42
- }
43
- /**
44
- * Return a new Runnable that maps a list of inputs to a list of outputs,
45
- * by calling invoke() with each input.
46
- */
47
- map() {
48
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
49
- return new RunnableEach({ bound: this });
50
- }
51
- /**
52
- * Add retry logic to an existing runnable.
53
- * @param kwargs
54
- * @returns A new RunnableRetry that, when invoked, will retry according to the parameters.
55
- */
56
- withRetry(fields) {
57
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
58
- return new RunnableRetry({
59
- bound: this,
60
- kwargs: {},
61
- config: {},
62
- maxAttemptNumber: fields?.stopAfterAttempt,
63
- ...fields,
64
- });
65
- }
66
- /**
67
- * Bind config to a Runnable, returning a new Runnable.
68
- * @param config New configuration parameters to attach to the new runnable.
69
- * @returns A new RunnableBinding with a config matching what's passed.
70
- */
71
- withConfig(config) {
72
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
73
- return new RunnableBinding({
74
- bound: this,
75
- config,
76
- kwargs: {},
77
- });
78
- }
79
- /**
80
- * Create a new runnable from the current one that will try invoking
81
- * other passed fallback runnables if the initial invocation fails.
82
- * @param fields.fallbacks Other runnables to call if the runnable errors.
83
- * @returns A new RunnableWithFallbacks.
84
- */
85
- withFallbacks(fields) {
86
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
87
- return new RunnableWithFallbacks({
88
- runnable: this,
89
- fallbacks: fields.fallbacks,
90
- });
91
- }
92
- _getOptionsList(options, length = 0) {
93
- if (Array.isArray(options)) {
94
- if (options.length !== length) {
95
- throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`);
96
- }
97
- return options;
98
- }
99
- return Array.from({ length }, () => options);
100
- }
101
- async batch(inputs, options, batchOptions) {
102
- const configList = this._getOptionsList(options ?? {}, inputs.length);
103
- const caller = new async_caller_js_1.AsyncCaller({
104
- maxConcurrency: batchOptions?.maxConcurrency,
105
- onFailedAttempt: (e) => {
106
- throw e;
107
- },
108
- });
109
- const batchCalls = inputs.map((input, i) => caller.call(async () => {
110
- try {
111
- const result = await this.invoke(input, configList[i]);
112
- return result;
113
- }
114
- catch (e) {
115
- if (batchOptions?.returnExceptions) {
116
- return e;
117
- }
118
- throw e;
119
- }
120
- }));
121
- return Promise.all(batchCalls);
122
- }
123
- /**
124
- * Default streaming implementation.
125
- * Subclasses should override this method if they support streaming output.
126
- * @param input
127
- * @param options
128
- */
129
- async *_streamIterator(input, options) {
130
- yield this.invoke(input, options);
131
- }
132
- /**
133
- * Stream output in chunks.
134
- * @param input
135
- * @param options
136
- * @returns A readable stream that is also an iterable.
137
- */
138
- async stream(input, options) {
139
- return stream_js_1.IterableReadableStream.fromAsyncGenerator(this._streamIterator(input, options));
140
- }
141
- _separateRunnableConfigFromCallOptions(options = {}) {
142
- const runnableConfig = {
143
- callbacks: options.callbacks,
144
- tags: options.tags,
145
- metadata: options.metadata,
146
- runName: options.runName,
147
- };
148
- const callOptions = { ...options };
149
- delete callOptions.callbacks;
150
- delete callOptions.tags;
151
- delete callOptions.metadata;
152
- delete callOptions.runName;
153
- return [runnableConfig, callOptions];
154
- }
155
- async _callWithConfig(func, input, options) {
156
- const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
157
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, options?.runType, undefined, undefined, options?.runName);
158
- let output;
159
- try {
160
- output = await func.bind(this)(input, options, runManager);
161
- }
162
- catch (e) {
163
- await runManager?.handleChainError(e);
164
- throw e;
165
- }
166
- await runManager?.handleChainEnd(_coerceToDict(output, "output"));
167
- return output;
168
- }
169
- /**
170
- * Internal method that handles batching and configuration for a runnable
171
- * It takes a function, input values, and optional configuration, and
172
- * returns a promise that resolves to the output values.
173
- * @param func The function to be executed for each input value.
174
- * @param input The input values to be processed.
175
- * @param config Optional configuration for the function execution.
176
- * @returns A promise that resolves to the output values.
177
- */
178
- async _batchWithConfig(func, inputs, options, batchOptions) {
179
- const optionsList = this._getOptionsList(options ?? {}, inputs.length);
180
- const callbackManagers = await Promise.all(optionsList.map(config_js_1.getCallbackMangerForConfig));
181
- const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), undefined, optionsList[i].runType, undefined, undefined, optionsList[i].runName)));
182
- let outputs;
183
- try {
184
- outputs = await func(inputs, optionsList, runManagers, batchOptions);
185
- }
186
- catch (e) {
187
- await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e)));
188
- throw e;
189
- }
190
- await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(outputs, "output"))));
191
- return outputs;
192
- }
193
- /**
194
- * Helper method to transform an Iterator of Input values into an Iterator of
195
- * Output values, with callbacks.
196
- * Use this to implement `stream()` or `transform()` in Runnable subclasses.
197
- */
198
- async *_transformStreamWithConfig(inputGenerator, transformer, options) {
199
- let finalInput;
200
- let finalInputSupported = true;
201
- let finalOutput;
202
- let finalOutputSupported = true;
203
- const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
204
- let runManager;
205
- const serializedRepresentation = this.toJSON();
206
- async function* wrapInputForTracing() {
207
- for await (const chunk of inputGenerator) {
208
- if (!runManager) {
209
- // Start the run manager AFTER the iterator starts to preserve
210
- // tracing order
211
- runManager = await callbackManager_?.handleChainStart(serializedRepresentation, { input: "" }, undefined, options?.runType, undefined, undefined, options?.runName);
212
- }
213
- if (finalInputSupported) {
214
- if (finalInput === undefined) {
215
- finalInput = chunk;
216
- }
217
- else {
218
- try {
219
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
220
- finalInput = finalInput.concat(chunk);
221
- }
222
- catch {
223
- finalInput = undefined;
224
- finalInputSupported = false;
225
- }
226
- }
227
- }
228
- yield chunk;
229
- }
230
- }
231
- const wrappedInputGenerator = wrapInputForTracing();
232
- try {
233
- const outputIterator = transformer(wrappedInputGenerator, runManager, options);
234
- for await (const chunk of outputIterator) {
235
- yield chunk;
236
- if (finalOutputSupported) {
237
- if (finalOutput === undefined) {
238
- finalOutput = chunk;
239
- }
240
- else {
241
- try {
242
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
243
- finalOutput = finalOutput.concat(chunk);
244
- }
245
- catch {
246
- finalOutput = undefined;
247
- finalOutputSupported = false;
248
- }
249
- }
250
- }
251
- }
252
- }
253
- catch (e) {
254
- await runManager?.handleChainError(e, undefined, undefined, undefined, {
255
- inputs: _coerceToDict(finalInput, "input"),
256
- });
257
- throw e;
258
- }
259
- await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: _coerceToDict(finalInput, "input") });
260
- }
261
- _patchConfig(config = {}, callbackManager = undefined) {
262
- const newConfig = { ...config };
263
- if (callbackManager !== undefined) {
264
- /**
265
- * If we're replacing callbacks we need to unset runName
266
- * since that should apply only to the same run as the original callbacks
267
- */
268
- delete newConfig.runName;
269
- return { ...newConfig, callbacks: callbackManager };
270
- }
271
- return newConfig;
272
- }
273
- /**
274
- * Create a new runnable sequence that runs each individual runnable in series,
275
- * piping the output of one runnable into another runnable or runnable-like.
276
- * @param coerceable A runnable, function, or object whose values are functions or runnables.
277
- * @returns A new runnable sequence.
278
- */
279
- pipe(coerceable) {
280
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
281
- return new RunnableSequence({
282
- first: this,
283
- last: _coerceToRunnable(coerceable),
284
- });
285
- }
286
- /**
287
- * Default implementation of transform, which buffers input and then calls stream.
288
- * Subclasses should override this method if they can start producing output while
289
- * input is still being generated.
290
- * @param generator
291
- * @param options
292
- */
293
- async *transform(generator, options) {
294
- let finalChunk;
295
- for await (const chunk of generator) {
296
- if (finalChunk === undefined) {
297
- finalChunk = chunk;
298
- }
299
- else {
300
- // Make a best effort to gather, for any type that supports concat.
301
- // This method should throw an error if gathering fails.
302
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
303
- finalChunk = finalChunk.concat(chunk);
304
- }
305
- }
306
- yield* this._streamIterator(finalChunk, options);
307
- }
308
- /**
309
- * Stream all output from a runnable, as reported to the callback system.
310
- * This includes all inner runs of LLMs, Retrievers, Tools, etc.
311
- * Output is streamed as Log objects, which include a list of
312
- * jsonpatch ops that describe how the state of the run has changed in each
313
- * step, and the final state of the run.
314
- * The jsonpatch ops can be applied in order to construct state.
315
- * @param input
316
- * @param options
317
- * @param streamOptions
318
- */
319
- async *streamLog(input, options, streamOptions) {
320
- const stream = new log_stream_js_1.LogStreamCallbackHandler({
321
- ...streamOptions,
322
- autoClose: false,
323
- });
324
- const config = options ?? {};
325
- const { callbacks } = config;
326
- if (callbacks === undefined) {
327
- config.callbacks = [stream];
328
- }
329
- else if (Array.isArray(callbacks)) {
330
- config.callbacks = callbacks.concat([stream]);
331
- }
332
- else {
333
- const copiedCallbacks = callbacks.copy();
334
- copiedCallbacks.inheritableHandlers.push(stream);
335
- config.callbacks = copiedCallbacks;
336
- }
337
- const runnableStream = await this.stream(input, config);
338
- async function consumeRunnableStream() {
339
- try {
340
- for await (const chunk of runnableStream) {
341
- const patch = new log_stream_js_1.RunLogPatch({
342
- ops: [
343
- {
344
- op: "add",
345
- path: "/streamed_output/-",
346
- value: chunk,
347
- },
348
- ],
349
- });
350
- await stream.writer.write(patch);
351
- }
352
- }
353
- finally {
354
- await stream.writer.close();
355
- }
356
- }
357
- const runnableStreamPromise = consumeRunnableStream();
358
- try {
359
- for await (const log of stream) {
360
- yield log;
361
- }
362
- }
363
- finally {
364
- await runnableStreamPromise;
365
- }
366
- }
367
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
368
- static isRunnable(thing) {
369
- return thing ? thing.lc_runnable : false;
370
- }
371
- }
372
- exports.Runnable = Runnable;
373
- /**
374
- * A runnable that delegates calls to another runnable with a set of kwargs.
375
- */
376
- class RunnableBinding extends Runnable {
377
- static lc_name() {
378
- return "RunnableBinding";
379
- }
380
- constructor(fields) {
381
- super(fields);
382
- Object.defineProperty(this, "lc_namespace", {
383
- enumerable: true,
384
- configurable: true,
385
- writable: true,
386
- value: ["langchain", "schema", "runnable"]
387
- });
388
- Object.defineProperty(this, "lc_serializable", {
389
- enumerable: true,
390
- configurable: true,
391
- writable: true,
392
- value: true
393
- });
394
- Object.defineProperty(this, "bound", {
395
- enumerable: true,
396
- configurable: true,
397
- writable: true,
398
- value: void 0
399
- });
400
- Object.defineProperty(this, "config", {
401
- enumerable: true,
402
- configurable: true,
403
- writable: true,
404
- value: void 0
405
- });
406
- Object.defineProperty(this, "kwargs", {
407
- enumerable: true,
408
- configurable: true,
409
- writable: true,
410
- value: void 0
411
- });
412
- this.bound = fields.bound;
413
- this.kwargs = fields.kwargs;
414
- this.config = fields.config;
415
- }
416
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
417
- _mergeConfig(options) {
418
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
419
- const copy = { ...this.config };
420
- if (options) {
421
- for (const key of Object.keys(options)) {
422
- if (key === "metadata") {
423
- copy[key] = { ...copy[key], ...options[key] };
424
- }
425
- else if (key === "tags") {
426
- copy[key] = (copy[key] ?? []).concat(options[key] ?? []);
427
- }
428
- else {
429
- copy[key] = options[key] ?? copy[key];
430
- }
431
- }
432
- }
433
- return copy;
434
- }
435
- bind(kwargs) {
436
- return this.constructor({
437
- bound: this.bound,
438
- kwargs: { ...this.kwargs, ...kwargs },
439
- config: this.config,
440
- });
441
- }
442
- withConfig(config) {
443
- return this.constructor({
444
- bound: this.bound,
445
- kwargs: this.kwargs,
446
- config: { ...this.config, ...config },
447
- });
448
- }
449
- withRetry(fields) {
450
- return this.constructor({
451
- bound: this.bound.withRetry(fields),
452
- kwargs: this.kwargs,
453
- config: this.config,
454
- });
455
- }
456
- async invoke(input, options) {
457
- return this.bound.invoke(input, this._mergeConfig({ ...options, ...this.kwargs }));
458
- }
459
- async batch(inputs, options, batchOptions) {
460
- const mergedOptions = Array.isArray(options)
461
- ? options.map((individualOption) => this._mergeConfig({
462
- ...individualOption,
463
- ...this.kwargs,
464
- }))
465
- : this._mergeConfig({ ...options, ...this.kwargs });
466
- return this.bound.batch(inputs, mergedOptions, batchOptions);
467
- }
468
- async *_streamIterator(input, options) {
469
- yield* this.bound._streamIterator(input, this._mergeConfig({ ...options, ...this.kwargs }));
470
- }
471
- async stream(input, options) {
472
- return this.bound.stream(input, this._mergeConfig({ ...options, ...this.kwargs }));
473
- }
474
- async *transform(
475
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
476
- generator, options) {
477
- yield* this.bound.transform(generator, this._mergeConfig({ ...options, ...this.kwargs }));
478
- }
479
- static isRunnableBinding(
480
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
481
- thing
482
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
483
- ) {
484
- return thing.bound && Runnable.isRunnable(thing.bound);
485
- }
486
- }
487
- exports.RunnableBinding = RunnableBinding;
488
- /**
489
- * A runnable that delegates calls to another runnable
490
- * with each element of the input sequence.
491
- */
492
- class RunnableEach extends Runnable {
493
- static lc_name() {
494
- return "RunnableEach";
495
- }
496
- constructor(fields) {
497
- super(fields);
498
- Object.defineProperty(this, "lc_serializable", {
499
- enumerable: true,
500
- configurable: true,
501
- writable: true,
502
- value: true
503
- });
504
- Object.defineProperty(this, "lc_namespace", {
505
- enumerable: true,
506
- configurable: true,
507
- writable: true,
508
- value: ["langchain", "schema", "runnable"]
509
- });
510
- Object.defineProperty(this, "bound", {
511
- enumerable: true,
512
- configurable: true,
513
- writable: true,
514
- value: void 0
515
- });
516
- this.bound = fields.bound;
517
- }
518
- /**
519
- * Binds the runnable with the specified arguments.
520
- * @param args The arguments to bind the runnable with.
521
- * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments.
522
- */
523
- bind(kwargs) {
524
- return new RunnableEach({
525
- bound: this.bound.bind(kwargs),
526
- });
527
- }
528
- /**
529
- * Invokes the runnable with the specified input and configuration.
530
- * @param input The input to invoke the runnable with.
531
- * @param config The configuration to invoke the runnable with.
532
- * @returns A promise that resolves to the output of the runnable.
533
- */
534
- async invoke(inputs, config) {
535
- return this._callWithConfig(this._invoke, inputs, config);
536
- }
537
- /**
538
- * A helper method that is used to invoke the runnable with the specified input and configuration.
539
- * @param input The input to invoke the runnable with.
540
- * @param config The configuration to invoke the runnable with.
541
- * @returns A promise that resolves to the output of the runnable.
542
- */
543
- async _invoke(inputs, config, runManager) {
544
- return this.bound.batch(inputs, this._patchConfig(config, runManager?.getChild()));
545
- }
546
- }
547
- exports.RunnableEach = RunnableEach;
548
- /**
549
- * Base class for runnables that can be retried a
550
- * specified number of times.
551
- */
552
- class RunnableRetry extends RunnableBinding {
553
- static lc_name() {
554
- return "RunnableRetry";
555
- }
556
- constructor(fields) {
557
- super(fields);
558
- Object.defineProperty(this, "lc_namespace", {
559
- enumerable: true,
560
- configurable: true,
561
- writable: true,
562
- value: ["langchain", "schema", "runnable"]
563
- });
564
- Object.defineProperty(this, "maxAttemptNumber", {
565
- enumerable: true,
566
- configurable: true,
567
- writable: true,
568
- value: 3
569
- });
570
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
571
- Object.defineProperty(this, "onFailedAttempt", {
572
- enumerable: true,
573
- configurable: true,
574
- writable: true,
575
- value: () => { }
576
- });
577
- this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber;
578
- this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt;
579
- }
580
- _patchConfigForRetry(attempt, config, runManager) {
581
- const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined;
582
- return this._patchConfig(config, runManager?.getChild(tag));
583
- }
584
- async _invoke(input, config, runManager) {
585
- return (0, p_retry_1.default)((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), {
586
- onFailedAttempt: this.onFailedAttempt,
587
- retries: Math.max(this.maxAttemptNumber - 1, 0),
588
- randomize: true,
589
- });
590
- }
591
- /**
592
- * Method that invokes the runnable with the specified input, run manager,
593
- * and config. It handles the retry logic by catching any errors and
594
- * recursively invoking itself with the updated config for the next retry
595
- * attempt.
596
- * @param input The input for the runnable.
597
- * @param runManager The run manager for the runnable.
598
- * @param config The config for the runnable.
599
- * @returns A promise that resolves to the output of the runnable.
600
- */
601
- async invoke(input, config) {
602
- return this._callWithConfig(this._invoke, input, config);
603
- }
604
- async _batch(inputs, configs, runManagers, batchOptions) {
605
- const resultsMap = {};
606
- try {
607
- await (0, p_retry_1.default)(async (attemptNumber) => {
608
- const remainingIndexes = inputs
609
- .map((_, i) => i)
610
- .filter((i) => resultsMap[i.toString()] === undefined ||
611
- // eslint-disable-next-line no-instanceof/no-instanceof
612
- resultsMap[i.toString()] instanceof Error);
613
- const remainingInputs = remainingIndexes.map((i) => inputs[i]);
614
- const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i]));
615
- const results = await super.batch(remainingInputs, patchedConfigs, {
616
- ...batchOptions,
617
- returnExceptions: true,
618
- });
619
- let firstException;
620
- for (let i = 0; i < results.length; i += 1) {
621
- const result = results[i];
622
- const resultMapIndex = remainingIndexes[i];
623
- // eslint-disable-next-line no-instanceof/no-instanceof
624
- if (result instanceof Error) {
625
- if (firstException === undefined) {
626
- firstException = result;
627
- }
628
- }
629
- resultsMap[resultMapIndex.toString()] = result;
630
- }
631
- if (firstException) {
632
- throw firstException;
633
- }
634
- return results;
635
- }, {
636
- onFailedAttempt: this.onFailedAttempt,
637
- retries: Math.max(this.maxAttemptNumber - 1, 0),
638
- randomize: true,
639
- });
640
- }
641
- catch (e) {
642
- if (batchOptions?.returnExceptions !== true) {
643
- throw e;
644
- }
645
- }
646
- return Object.keys(resultsMap)
647
- .sort((a, b) => parseInt(a, 10) - parseInt(b, 10))
648
- .map((key) => resultsMap[parseInt(key, 10)]);
649
- }
650
- async batch(inputs, options, batchOptions) {
651
- return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions);
652
- }
653
- }
654
- exports.RunnableRetry = RunnableRetry;
655
- /**
656
- * A sequence of runnables, where the output of each is the input of the next.
657
- * @example
658
- * ```typescript
659
- * const promptTemplate = PromptTemplate.fromTemplate(
660
- * "Tell me a joke about {topic}",
661
- * );
662
- * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({})]);
663
- * const result = await chain.invoke({ topic: "bears" });
664
- * ```
665
- */
666
- class RunnableSequence extends Runnable {
667
- static lc_name() {
668
- return "RunnableSequence";
669
- }
670
- constructor(fields) {
671
- super(fields);
672
- Object.defineProperty(this, "first", {
673
- enumerable: true,
674
- configurable: true,
675
- writable: true,
676
- value: void 0
677
- });
678
- Object.defineProperty(this, "middle", {
679
- enumerable: true,
680
- configurable: true,
681
- writable: true,
682
- value: []
683
- });
684
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
685
- Object.defineProperty(this, "last", {
686
- enumerable: true,
687
- configurable: true,
688
- writable: true,
689
- value: void 0
690
- });
691
- Object.defineProperty(this, "lc_serializable", {
692
- enumerable: true,
693
- configurable: true,
694
- writable: true,
695
- value: true
696
- });
697
- Object.defineProperty(this, "lc_namespace", {
698
- enumerable: true,
699
- configurable: true,
700
- writable: true,
701
- value: ["langchain", "schema", "runnable"]
702
- });
703
- this.first = fields.first;
704
- this.middle = fields.middle ?? this.middle;
705
- this.last = fields.last;
706
- }
707
- get steps() {
708
- return [this.first, ...this.middle, this.last];
709
- }
710
- async invoke(input, options) {
711
- const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
712
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, undefined, undefined, undefined, options?.runName);
713
- let nextStepInput = input;
714
- let finalOutput;
715
- try {
716
- const initialSteps = [this.first, ...this.middle];
717
- for (let i = 0; i < initialSteps.length; i += 1) {
718
- const step = initialSteps[i];
719
- nextStepInput = await step.invoke(nextStepInput, this._patchConfig(options, runManager?.getChild(`seq:step:${i + 1}`)));
720
- }
721
- // TypeScript can't detect that the last output of the sequence returns RunOutput, so call it out of the loop here
722
- finalOutput = await this.last.invoke(nextStepInput, this._patchConfig(options, runManager?.getChild(`seq:step:${this.steps.length}`)));
723
- }
724
- catch (e) {
725
- await runManager?.handleChainError(e);
726
- throw e;
727
- }
728
- await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output"));
729
- return finalOutput;
730
- }
731
- async batch(inputs, options, batchOptions) {
732
- const configList = this._getOptionsList(options ?? {}, inputs.length);
733
- const callbackManagers = await Promise.all(configList.map(config_js_1.getCallbackMangerForConfig));
734
- const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), undefined, undefined, undefined, undefined, configList[i].runName)));
735
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
736
- let nextStepInputs = inputs;
737
- let finalOutputs;
738
- try {
739
- const initialSteps = [this.first, ...this.middle];
740
- for (let i = 0; i < initialSteps.length; i += 1) {
741
- const step = initialSteps[i];
742
- nextStepInputs = await step.batch(nextStepInputs, runManagers.map((runManager, j) => this._patchConfig(configList[j], runManager?.getChild(`seq:step:${i + 1}`))), batchOptions);
743
- }
744
- finalOutputs = await this.last.batch(nextStepInputs, runManagers.map((runManager) => this._patchConfig(configList[this.steps.length - 1], runManager?.getChild(`seq:step:${this.steps.length}`))), batchOptions);
745
- }
746
- catch (e) {
747
- await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e)));
748
- throw e;
749
- }
750
- await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict(finalOutputs[i], "output"))));
751
- return finalOutputs;
752
- }
753
- async *_streamIterator(input, options) {
754
- const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
755
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, undefined, undefined, undefined, options?.runName);
756
- let nextStepInput = input;
757
- const steps = [this.first, ...this.middle, this.last];
758
- // Find the index of the last runnable in the sequence that doesn't have an overridden .transform() method
759
- // and start streaming from there
760
- const streamingStartStepIndex = Math.min(steps.length - 1, steps.length -
761
- [...steps].reverse().findIndex((step) => {
762
- const isDefaultImplementation = step.transform === Runnable.prototype.transform;
763
- const boundRunnableIsDefaultImplementation = RunnableBinding.isRunnableBinding(step) &&
764
- step.bound?.transform === Runnable.prototype.transform;
765
- return (isDefaultImplementation || boundRunnableIsDefaultImplementation);
766
- }) -
767
- 1);
768
- try {
769
- const invokeSteps = steps.slice(0, streamingStartStepIndex);
770
- for (let i = 0; i < invokeSteps.length; i += 1) {
771
- const step = invokeSteps[i];
772
- nextStepInput = await step.invoke(nextStepInput, this._patchConfig(options, runManager?.getChild(`seq:step:${i + 1}`)));
773
- }
774
- }
775
- catch (e) {
776
- await runManager?.handleChainError(e);
777
- throw e;
778
- }
779
- let concatSupported = true;
780
- let finalOutput;
781
- try {
782
- let finalGenerator = await steps[streamingStartStepIndex]._streamIterator(nextStepInput, this._patchConfig(options, runManager?.getChild(`seq:step:${streamingStartStepIndex + 1}`)));
783
- const finalSteps = steps.slice(streamingStartStepIndex + 1);
784
- for (let i = 0; i < finalSteps.length; i += 1) {
785
- const step = finalSteps[i];
786
- finalGenerator = await step.transform(finalGenerator, this._patchConfig(options, runManager?.getChild(`seq:step:${streamingStartStepIndex + i + 2}`)));
787
- }
788
- for await (const chunk of finalGenerator) {
789
- yield chunk;
790
- if (concatSupported) {
791
- if (finalOutput === undefined) {
792
- finalOutput = chunk;
793
- }
794
- else {
795
- try {
796
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
797
- finalOutput = finalOutput.concat(chunk);
798
- }
799
- catch (e) {
800
- finalOutput = undefined;
801
- concatSupported = false;
802
- }
803
- }
804
- }
805
- }
806
- }
807
- catch (e) {
808
- await runManager?.handleChainError(e);
809
- throw e;
810
- }
811
- await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output"));
812
- }
813
- pipe(coerceable) {
814
- if (RunnableSequence.isRunnableSequence(coerceable)) {
815
- return new RunnableSequence({
816
- first: this.first,
817
- middle: this.middle.concat([
818
- this.last,
819
- coerceable.first,
820
- ...coerceable.middle,
821
- ]),
822
- last: coerceable.last,
823
- });
824
- }
825
- else {
826
- return new RunnableSequence({
827
- first: this.first,
828
- middle: [...this.middle, this.last],
829
- last: _coerceToRunnable(coerceable),
830
- });
831
- }
832
- }
833
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
834
- static isRunnableSequence(thing) {
835
- return Array.isArray(thing.middle) && Runnable.isRunnable(thing);
836
- }
837
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
838
- static from([first, ...runnables]) {
839
- return new RunnableSequence({
840
- first: _coerceToRunnable(first),
841
- middle: runnables.slice(0, -1).map(_coerceToRunnable),
842
- last: _coerceToRunnable(runnables[runnables.length - 1]),
843
- });
844
- }
845
- }
846
- exports.RunnableSequence = RunnableSequence;
847
- /**
848
- * A runnable that runs a mapping of runnables in parallel,
849
- * and returns a mapping of their outputs.
850
- * @example
851
- * ```typescript
852
- * const mapChain = RunnableMap.from({
853
- * joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe(
854
- * new ChatAnthropic({}),
855
- * ),
856
- * poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe(
857
- * new ChatAnthropic({}),
858
- * ),
859
- * });
860
- * const result = await mapChain.invoke({ topic: "bear" });
861
- * ```
862
- */
863
- class RunnableMap extends Runnable {
864
- static lc_name() {
865
- return "RunnableMap";
866
- }
867
- getStepsKeys() {
868
- return Object.keys(this.steps);
869
- }
870
- constructor(fields) {
871
- super(fields);
872
- Object.defineProperty(this, "lc_namespace", {
873
- enumerable: true,
874
- configurable: true,
875
- writable: true,
876
- value: ["langchain", "schema", "runnable"]
877
- });
878
- Object.defineProperty(this, "lc_serializable", {
879
- enumerable: true,
880
- configurable: true,
881
- writable: true,
882
- value: true
883
- });
884
- Object.defineProperty(this, "steps", {
885
- enumerable: true,
886
- configurable: true,
887
- writable: true,
888
- value: void 0
889
- });
890
- this.steps = {};
891
- for (const [key, value] of Object.entries(fields.steps)) {
892
- this.steps[key] = _coerceToRunnable(value);
893
- }
894
- }
895
- static from(steps) {
896
- return new RunnableMap({ steps });
897
- }
898
- async invoke(input, options
899
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
900
- ) {
901
- const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
902
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), {
903
- input,
904
- }, undefined, undefined, undefined, undefined, options?.runName);
905
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
906
- const output = {};
907
- try {
908
- await Promise.all(Object.entries(this.steps).map(async ([key, runnable]) => {
909
- output[key] = await runnable.invoke(input, this._patchConfig(options, runManager?.getChild(key)));
910
- }));
911
- }
912
- catch (e) {
913
- await runManager?.handleChainError(e);
914
- throw e;
915
- }
916
- await runManager?.handleChainEnd(output);
917
- return output;
918
- }
919
- }
920
- exports.RunnableMap = RunnableMap;
921
- /**
922
- * A runnable that runs a callable.
923
- */
924
- class RunnableLambda extends Runnable {
925
- static lc_name() {
926
- return "RunnableLambda";
927
- }
928
- constructor(fields) {
929
- super(fields);
930
- Object.defineProperty(this, "lc_namespace", {
931
- enumerable: true,
932
- configurable: true,
933
- writable: true,
934
- value: ["langchain", "schema", "runnable"]
935
- });
936
- Object.defineProperty(this, "func", {
937
- enumerable: true,
938
- configurable: true,
939
- writable: true,
940
- value: void 0
941
- });
942
- this.func = fields.func;
943
- }
944
- static from(func) {
945
- return new RunnableLambda({
946
- func,
947
- });
948
- }
949
- async _invoke(input, config, runManager) {
950
- let output = await this.func(input);
951
- if (output && Runnable.isRunnable(output)) {
952
- output = await output.invoke(input, this._patchConfig(config, runManager?.getChild()));
953
- }
954
- return output;
955
- }
956
- async invoke(input, options) {
957
- return this._callWithConfig(this._invoke, input, options);
958
- }
959
- }
960
- exports.RunnableLambda = RunnableLambda;
961
- /**
962
- * A Runnable that can fallback to other Runnables if it fails.
963
- */
964
- class RunnableWithFallbacks extends Runnable {
965
- static lc_name() {
966
- return "RunnableWithFallbacks";
967
- }
968
- constructor(fields) {
969
- super(fields);
970
- Object.defineProperty(this, "lc_namespace", {
971
- enumerable: true,
972
- configurable: true,
973
- writable: true,
974
- value: ["langchain", "schema", "runnable"]
975
- });
976
- Object.defineProperty(this, "lc_serializable", {
977
- enumerable: true,
978
- configurable: true,
979
- writable: true,
980
- value: true
981
- });
982
- Object.defineProperty(this, "runnable", {
983
- enumerable: true,
984
- configurable: true,
985
- writable: true,
986
- value: void 0
987
- });
988
- Object.defineProperty(this, "fallbacks", {
989
- enumerable: true,
990
- configurable: true,
991
- writable: true,
992
- value: void 0
993
- });
994
- this.runnable = fields.runnable;
995
- this.fallbacks = fields.fallbacks;
996
- }
997
- *runnables() {
998
- yield this.runnable;
999
- for (const fallback of this.fallbacks) {
1000
- yield fallback;
1001
- }
1002
- }
1003
- async invoke(input, options) {
1004
- const callbackManager_ = await manager_js_1.CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);
1005
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, undefined, undefined, undefined, options?.runName);
1006
- let firstError;
1007
- for (const runnable of this.runnables()) {
1008
- try {
1009
- const output = await runnable.invoke(input, this._patchConfig(options, runManager?.getChild()));
1010
- await runManager?.handleChainEnd(_coerceToDict(output, "output"));
1011
- return output;
1012
- }
1013
- catch (e) {
1014
- if (firstError === undefined) {
1015
- firstError = e;
1016
- }
1017
- }
1018
- }
1019
- if (firstError === undefined) {
1020
- throw new Error("No error stored at end of fallback.");
1021
- }
1022
- await runManager?.handleChainError(firstError);
1023
- throw firstError;
1024
- }
1025
- async batch(inputs, options, batchOptions) {
1026
- if (batchOptions?.returnExceptions) {
1027
- throw new Error("Not implemented.");
1028
- }
1029
- const configList = this._getOptionsList(options ?? {}, inputs.length);
1030
- const callbackManagers = await Promise.all(configList.map((config) => manager_js_1.CallbackManager.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata)));
1031
- const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), undefined, undefined, undefined, undefined, configList[i].runName)));
1032
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1033
- let firstError;
1034
- for (const runnable of this.runnables()) {
1035
- try {
1036
- const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => this._patchConfig(configList[j], runManager?.getChild())), batchOptions);
1037
- await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict(outputs[i], "output"))));
1038
- return outputs;
1039
- }
1040
- catch (e) {
1041
- if (firstError === undefined) {
1042
- firstError = e;
1043
- }
1044
- }
1045
- }
1046
- if (!firstError) {
1047
- throw new Error("No error stored at end of fallbacks.");
1048
- }
1049
- await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError)));
1050
- throw firstError;
1051
- }
1052
- }
1053
- exports.RunnableWithFallbacks = RunnableWithFallbacks;
1054
- // TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type
1055
- function _coerceToRunnable(coerceable) {
1056
- if (typeof coerceable === "function") {
1057
- return new RunnableLambda({ func: coerceable });
1058
- }
1059
- else if (Runnable.isRunnable(coerceable)) {
1060
- return coerceable;
1061
- }
1062
- else if (!Array.isArray(coerceable) && typeof coerceable === "object") {
1063
- const runnables = {};
1064
- for (const [key, value] of Object.entries(coerceable)) {
1065
- runnables[key] = _coerceToRunnable(value);
1066
- }
1067
- return new RunnableMap({
1068
- steps: runnables,
1069
- });
1070
- }
1071
- else {
1072
- throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`);
1073
- }
1074
- }
1075
- exports._coerceToRunnable = _coerceToRunnable;
4
+ var runnables_1 = require("langchain-core/runnables");
5
+ Object.defineProperty(exports, "Runnable", { enumerable: true, get: function () { return runnables_1.Runnable; } });
6
+ Object.defineProperty(exports, "RunnableBinding", { enumerable: true, get: function () { return runnables_1.RunnableBinding; } });
7
+ Object.defineProperty(exports, "RunnableEach", { enumerable: true, get: function () { return runnables_1.RunnableEach; } });
8
+ Object.defineProperty(exports, "RunnableRetry", { enumerable: true, get: function () { return runnables_1.RunnableRetry; } });
9
+ Object.defineProperty(exports, "RunnableSequence", { enumerable: true, get: function () { return runnables_1.RunnableSequence; } });
10
+ Object.defineProperty(exports, "RunnableMap", { enumerable: true, get: function () { return runnables_1.RunnableMap; } });
11
+ Object.defineProperty(exports, "RunnableLambda", { enumerable: true, get: function () { return runnables_1.RunnableLambda; } });
12
+ Object.defineProperty(exports, "RunnableWithFallbacks", { enumerable: true, get: function () { return runnables_1.RunnableWithFallbacks; } });
13
+ Object.defineProperty(exports, "_coerceToRunnable", { enumerable: true, get: function () { return runnables_1._coerceToRunnable; } });