langchain 0.0.197-rc.0 → 0.0.197-rc.1

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 (202) hide show
  1. package/dist/agents/executor.cjs +351 -1
  2. package/dist/agents/executor.d.ts +61 -3
  3. package/dist/agents/executor.js +350 -1
  4. package/dist/agents/toolkits/conversational_retrieval/token_buffer_memory.d.ts +1 -1
  5. package/dist/base_language/count_tokens.cjs +1 -1
  6. package/dist/base_language/count_tokens.d.ts +1 -1
  7. package/dist/base_language/count_tokens.js +1 -1
  8. package/dist/base_language/index.cjs +1 -1
  9. package/dist/base_language/index.d.ts +1 -1
  10. package/dist/base_language/index.js +1 -1
  11. package/dist/cache/base.cjs +1 -1
  12. package/dist/cache/base.d.ts +1 -1
  13. package/dist/cache/base.js +1 -1
  14. package/dist/cache/index.cjs +1 -1
  15. package/dist/cache/index.d.ts +1 -1
  16. package/dist/cache/index.js +1 -1
  17. package/dist/callbacks/base.cjs +1 -1
  18. package/dist/callbacks/base.d.ts +1 -1
  19. package/dist/callbacks/base.js +1 -1
  20. package/dist/callbacks/handlers/console.cjs +1 -1
  21. package/dist/callbacks/handlers/console.d.ts +1 -1
  22. package/dist/callbacks/handlers/console.js +1 -1
  23. package/dist/callbacks/handlers/initialize.cjs +1 -1
  24. package/dist/callbacks/handlers/initialize.d.ts +1 -1
  25. package/dist/callbacks/handlers/initialize.js +1 -1
  26. package/dist/callbacks/handlers/log_stream.cjs +1 -1
  27. package/dist/callbacks/handlers/log_stream.d.ts +1 -1
  28. package/dist/callbacks/handlers/log_stream.js +1 -1
  29. package/dist/callbacks/handlers/run_collector.cjs +1 -1
  30. package/dist/callbacks/handlers/run_collector.d.ts +1 -1
  31. package/dist/callbacks/handlers/run_collector.js +1 -1
  32. package/dist/callbacks/handlers/tracer.cjs +1 -1
  33. package/dist/callbacks/handlers/tracer.d.ts +1 -1
  34. package/dist/callbacks/handlers/tracer.js +1 -1
  35. package/dist/callbacks/handlers/tracer_langchain.cjs +1 -1
  36. package/dist/callbacks/handlers/tracer_langchain.d.ts +1 -1
  37. package/dist/callbacks/handlers/tracer_langchain.js +1 -1
  38. package/dist/callbacks/handlers/tracer_langchain_v1.cjs +1 -1
  39. package/dist/callbacks/handlers/tracer_langchain_v1.d.ts +1 -1
  40. package/dist/callbacks/handlers/tracer_langchain_v1.js +1 -1
  41. package/dist/callbacks/manager.cjs +1 -1
  42. package/dist/callbacks/manager.d.ts +1 -1
  43. package/dist/callbacks/manager.js +1 -1
  44. package/dist/callbacks/promises.cjs +1 -1
  45. package/dist/callbacks/promises.d.ts +1 -1
  46. package/dist/callbacks/promises.js +1 -1
  47. package/dist/chains/base.cjs +16 -0
  48. package/dist/chains/base.d.ts +2 -0
  49. package/dist/chains/base.js +16 -0
  50. package/dist/chains/openai_functions/structured_output.cjs +1 -1
  51. package/dist/chains/openai_functions/structured_output.d.ts +1 -1
  52. package/dist/chains/openai_functions/structured_output.js +1 -1
  53. package/dist/chains/openai_moderation.cjs +2 -2
  54. package/dist/chains/openai_moderation.d.ts +1 -1
  55. package/dist/chains/openai_moderation.js +1 -1
  56. package/dist/chat_models/base.cjs +1 -1
  57. package/dist/chat_models/base.d.ts +1 -1
  58. package/dist/chat_models/base.js +1 -1
  59. package/dist/chat_models/fireworks.d.ts +2 -2
  60. package/dist/chat_models/iflytek_xinghuo/common.d.ts +1 -1
  61. package/dist/chat_models/minimax.d.ts +2 -2
  62. package/dist/chat_models/openai.cjs +4 -698
  63. package/dist/chat_models/openai.d.ts +4 -137
  64. package/dist/chat_models/openai.js +2 -695
  65. package/dist/document.cjs +1 -1
  66. package/dist/document.d.ts +1 -1
  67. package/dist/document.js +1 -1
  68. package/dist/document_loaders/fs/openai_whisper_audio.cjs +2 -2
  69. package/dist/document_loaders/fs/openai_whisper_audio.d.ts +1 -1
  70. package/dist/document_loaders/fs/openai_whisper_audio.js +1 -1
  71. package/dist/document_loaders/web/azure_blob_storage_file.d.ts +1 -1
  72. package/dist/document_loaders/web/s3.d.ts +1 -1
  73. package/dist/embeddings/base.cjs +1 -1
  74. package/dist/embeddings/base.d.ts +1 -1
  75. package/dist/embeddings/base.js +1 -1
  76. package/dist/embeddings/cache_backed.cjs +1 -1
  77. package/dist/embeddings/cache_backed.js +1 -1
  78. package/dist/embeddings/openai.cjs +2 -240
  79. package/dist/embeddings/openai.d.ts +1 -82
  80. package/dist/embeddings/openai.js +1 -239
  81. package/dist/experimental/openai_assistant/index.cjs +3 -3
  82. package/dist/experimental/openai_assistant/index.d.ts +1 -1
  83. package/dist/experimental/openai_assistant/index.js +1 -1
  84. package/dist/experimental/openai_assistant/schema.d.ts +1 -1
  85. package/dist/experimental/openai_files/index.cjs +2 -2
  86. package/dist/experimental/openai_files/index.d.ts +1 -1
  87. package/dist/experimental/openai_files/index.js +1 -1
  88. package/dist/experimental/plan_and_execute/prompt.d.ts +1 -1
  89. package/dist/llms/base.cjs +1 -1
  90. package/dist/llms/base.d.ts +1 -1
  91. package/dist/llms/base.js +1 -1
  92. package/dist/llms/fireworks.d.ts +2 -2
  93. package/dist/llms/openai-chat.cjs +3 -445
  94. package/dist/llms/openai-chat.d.ts +4 -123
  95. package/dist/llms/openai-chat.js +2 -443
  96. package/dist/llms/openai.cjs +6 -530
  97. package/dist/llms/openai.d.ts +4 -123
  98. package/dist/llms/openai.js +2 -525
  99. package/dist/load/index.cjs +4 -2
  100. package/dist/load/index.d.ts +2 -2
  101. package/dist/load/index.js +4 -2
  102. package/dist/load/serializable.cjs +1 -1
  103. package/dist/load/serializable.d.ts +1 -1
  104. package/dist/load/serializable.js +1 -1
  105. package/dist/memory/base.cjs +2 -2
  106. package/dist/memory/base.d.ts +2 -2
  107. package/dist/memory/base.js +2 -2
  108. package/dist/output_parsers/list.cjs +1 -1
  109. package/dist/output_parsers/list.d.ts +1 -1
  110. package/dist/output_parsers/list.js +1 -1
  111. package/dist/output_parsers/openai_functions.cjs +1 -1
  112. package/dist/output_parsers/openai_functions.d.ts +1 -1
  113. package/dist/output_parsers/openai_functions.js +1 -1
  114. package/dist/output_parsers/structured.d.ts +1 -1
  115. package/dist/prompts/base.cjs +3 -3
  116. package/dist/prompts/base.d.ts +3 -3
  117. package/dist/prompts/base.js +3 -3
  118. package/dist/prompts/chat.cjs +2 -2
  119. package/dist/prompts/chat.d.ts +2 -2
  120. package/dist/prompts/chat.js +2 -2
  121. package/dist/prompts/few_shot.cjs +1 -1
  122. package/dist/prompts/few_shot.d.ts +1 -1
  123. package/dist/prompts/few_shot.js +1 -1
  124. package/dist/prompts/index.cjs +1 -1
  125. package/dist/prompts/index.d.ts +1 -1
  126. package/dist/prompts/index.js +1 -1
  127. package/dist/prompts/pipeline.cjs +1 -1
  128. package/dist/prompts/pipeline.d.ts +1 -1
  129. package/dist/prompts/pipeline.js +1 -1
  130. package/dist/prompts/prompt.cjs +1 -1
  131. package/dist/prompts/prompt.d.ts +1 -1
  132. package/dist/prompts/prompt.js +1 -1
  133. package/dist/prompts/selectors/LengthBasedExampleSelector.cjs +1 -1
  134. package/dist/prompts/selectors/LengthBasedExampleSelector.d.ts +1 -1
  135. package/dist/prompts/selectors/LengthBasedExampleSelector.js +1 -1
  136. package/dist/prompts/selectors/SemanticSimilarityExampleSelector.cjs +1 -1
  137. package/dist/prompts/selectors/SemanticSimilarityExampleSelector.d.ts +1 -1
  138. package/dist/prompts/selectors/SemanticSimilarityExampleSelector.js +1 -1
  139. package/dist/prompts/selectors/conditional.cjs +1 -1
  140. package/dist/prompts/selectors/conditional.d.ts +1 -1
  141. package/dist/prompts/selectors/conditional.js +1 -1
  142. package/dist/prompts/serde.d.ts +1 -1
  143. package/dist/prompts/template.cjs +1 -1
  144. package/dist/prompts/template.d.ts +1 -1
  145. package/dist/prompts/template.js +1 -1
  146. package/dist/runnables/index.cjs +1 -1
  147. package/dist/runnables/index.d.ts +1 -1
  148. package/dist/runnables/index.js +1 -1
  149. package/dist/schema/document.cjs +1 -1
  150. package/dist/schema/document.d.ts +1 -1
  151. package/dist/schema/document.js +1 -1
  152. package/dist/schema/index.cjs +7 -7
  153. package/dist/schema/index.d.ts +11 -11
  154. package/dist/schema/index.js +7 -7
  155. package/dist/schema/output_parser.cjs +1 -1
  156. package/dist/schema/output_parser.d.ts +1 -1
  157. package/dist/schema/output_parser.js +1 -1
  158. package/dist/schema/retriever.cjs +1 -1
  159. package/dist/schema/retriever.d.ts +1 -1
  160. package/dist/schema/retriever.js +1 -1
  161. package/dist/schema/runnable/base.cjs +1 -1
  162. package/dist/schema/runnable/base.d.ts +1 -1
  163. package/dist/schema/runnable/base.js +1 -1
  164. package/dist/schema/runnable/branch.cjs +1 -1
  165. package/dist/schema/runnable/branch.d.ts +1 -1
  166. package/dist/schema/runnable/branch.js +1 -1
  167. package/dist/schema/runnable/config.d.ts +1 -1
  168. package/dist/schema/runnable/index.cjs +1 -1
  169. package/dist/schema/runnable/index.d.ts +1 -1
  170. package/dist/schema/runnable/index.js +1 -1
  171. package/dist/schema/runnable/passthrough.cjs +1 -1
  172. package/dist/schema/runnable/passthrough.d.ts +1 -1
  173. package/dist/schema/runnable/passthrough.js +1 -1
  174. package/dist/schema/runnable/router.cjs +1 -1
  175. package/dist/schema/runnable/router.d.ts +1 -1
  176. package/dist/schema/runnable/router.js +1 -1
  177. package/dist/schema/storage.cjs +1 -1
  178. package/dist/schema/storage.d.ts +1 -1
  179. package/dist/schema/storage.js +1 -1
  180. package/dist/tools/base.cjs +4 -108
  181. package/dist/tools/base.d.ts +1 -72
  182. package/dist/tools/base.js +1 -105
  183. package/dist/tools/bingserpapi.d.ts +1 -1
  184. package/dist/tools/convert_to_openai.cjs +4 -38
  185. package/dist/tools/convert_to_openai.d.ts +1 -11
  186. package/dist/tools/convert_to_openai.js +1 -35
  187. package/dist/tools/searchapi.d.ts +1 -1
  188. package/dist/tools/serpapi.d.ts +1 -1
  189. package/dist/tools/serper.d.ts +1 -1
  190. package/dist/types/openai-types.d.ts +1 -133
  191. package/dist/util/async_caller.cjs +1 -1
  192. package/dist/util/async_caller.d.ts +1 -1
  193. package/dist/util/async_caller.js +1 -1
  194. package/dist/util/openai.cjs +2 -18
  195. package/dist/util/openai.d.ts +1 -1
  196. package/dist/util/openai.js +1 -17
  197. package/dist/util/openapi.d.ts +2 -2
  198. package/dist/util/prompt-layer.d.ts +1 -1
  199. package/package.json +6 -5
  200. package/dist/util/openai-format-fndef.cjs +0 -81
  201. package/dist/util/openai-format-fndef.d.ts +0 -44
  202. package/dist/util/openai-format-fndef.js +0 -77
@@ -1,11 +1,215 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AgentExecutor = exports.ExceptionTool = void 0;
3
+ exports.AgentExecutor = exports.ExceptionTool = exports.AgentExecutorIterator = void 0;
4
4
  const base_js_1 = require("../chains/base.cjs");
5
5
  const agent_js_1 = require("./agent.cjs");
6
+ const manager_js_1 = require("../callbacks/manager.cjs");
6
7
  const output_parser_js_1 = require("../schema/output_parser.cjs");
7
8
  const base_js_2 = require("../tools/base.cjs");
8
9
  const base_js_3 = require("../schema/runnable/base.cjs");
10
+ const serializable_js_1 = require("../load/serializable.cjs");
11
+ class AgentExecutorIterator extends serializable_js_1.Serializable {
12
+ get finalOutputs() {
13
+ return this._finalOutputs;
14
+ }
15
+ /** Intended to be used as a setter method, needs to be async. */
16
+ async setFinalOutputs(value) {
17
+ this._finalOutputs = undefined;
18
+ if (value) {
19
+ const preparedOutputs = await this.agentExecutor.prepOutputs(this.inputs, value, true);
20
+ this._finalOutputs = preparedOutputs;
21
+ }
22
+ }
23
+ get nameToToolMap() {
24
+ const toolMap = this.agentExecutor.tools.map((tool) => ({
25
+ [tool.name]: tool,
26
+ }));
27
+ return Object.assign({}, ...toolMap);
28
+ }
29
+ constructor(fields) {
30
+ super(fields);
31
+ Object.defineProperty(this, "lc_namespace", {
32
+ enumerable: true,
33
+ configurable: true,
34
+ writable: true,
35
+ value: ["langchain", "agents", "executor_iterator"]
36
+ });
37
+ Object.defineProperty(this, "agentExecutor", {
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true,
41
+ value: void 0
42
+ });
43
+ Object.defineProperty(this, "inputs", {
44
+ enumerable: true,
45
+ configurable: true,
46
+ writable: true,
47
+ value: void 0
48
+ });
49
+ Object.defineProperty(this, "callbacks", {
50
+ enumerable: true,
51
+ configurable: true,
52
+ writable: true,
53
+ value: void 0
54
+ });
55
+ Object.defineProperty(this, "tags", {
56
+ enumerable: true,
57
+ configurable: true,
58
+ writable: true,
59
+ value: void 0
60
+ });
61
+ Object.defineProperty(this, "metadata", {
62
+ enumerable: true,
63
+ configurable: true,
64
+ writable: true,
65
+ value: void 0
66
+ });
67
+ Object.defineProperty(this, "runName", {
68
+ enumerable: true,
69
+ configurable: true,
70
+ writable: true,
71
+ value: void 0
72
+ });
73
+ Object.defineProperty(this, "_finalOutputs", {
74
+ enumerable: true,
75
+ configurable: true,
76
+ writable: true,
77
+ value: void 0
78
+ });
79
+ Object.defineProperty(this, "runManager", {
80
+ enumerable: true,
81
+ configurable: true,
82
+ writable: true,
83
+ value: void 0
84
+ });
85
+ Object.defineProperty(this, "intermediateSteps", {
86
+ enumerable: true,
87
+ configurable: true,
88
+ writable: true,
89
+ value: []
90
+ });
91
+ Object.defineProperty(this, "iterations", {
92
+ enumerable: true,
93
+ configurable: true,
94
+ writable: true,
95
+ value: 0
96
+ });
97
+ this.agentExecutor = fields.agentExecutor;
98
+ this.inputs = fields.inputs;
99
+ this.tags = fields.tags;
100
+ this.metadata = fields.metadata;
101
+ this.runName = fields.runName;
102
+ this.runManager = fields.runManager;
103
+ }
104
+ /**
105
+ * Reset the iterator to its initial state, clearing intermediate steps,
106
+ * iterations, and the final output.
107
+ */
108
+ reset() {
109
+ this.intermediateSteps = [];
110
+ this.iterations = 0;
111
+ this._finalOutputs = undefined;
112
+ }
113
+ updateIterations() {
114
+ this.iterations += 1;
115
+ }
116
+ async *streamIterator() {
117
+ this.reset();
118
+ // Loop to handle iteration
119
+ while (true) {
120
+ try {
121
+ if (this.iterations === 0) {
122
+ await this.onFirstStep();
123
+ }
124
+ const result = await this._callNext();
125
+ yield result;
126
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
127
+ }
128
+ catch (e) {
129
+ if ("message" in e &&
130
+ e.message.startsWith("Final outputs already reached: ")) {
131
+ if (!this.finalOutputs) {
132
+ throw e;
133
+ }
134
+ return this.finalOutputs;
135
+ }
136
+ if (this.runManager) {
137
+ await this.runManager.handleChainError(e);
138
+ }
139
+ throw e;
140
+ }
141
+ }
142
+ }
143
+ /**
144
+ * Perform any necessary setup for the first step
145
+ * of the asynchronous iterator.
146
+ */
147
+ async onFirstStep() {
148
+ if (this.iterations === 0) {
149
+ const callbackManager = await manager_js_1.CallbackManager.configure(this.callbacks, this.agentExecutor.callbacks, this.tags, this.agentExecutor.tags, this.metadata, this.agentExecutor.metadata, {
150
+ verbose: this.agentExecutor.verbose,
151
+ });
152
+ this.runManager = await callbackManager?.handleChainStart(this.agentExecutor.toJSON(), this.inputs, undefined, undefined, this.tags, this.metadata, this.runName);
153
+ }
154
+ }
155
+ /**
156
+ * Execute the next step in the chain using the
157
+ * AgentExecutor's _takeNextStep method.
158
+ */
159
+ async _executeNextStep(runManager) {
160
+ return this.agentExecutor._takeNextStep(this.nameToToolMap, this.inputs, this.intermediateSteps, runManager);
161
+ }
162
+ /**
163
+ * Process the output of the next step,
164
+ * handling AgentFinish and tool return cases.
165
+ */
166
+ async _processNextStepOutput(nextStepOutput, runManager) {
167
+ if ("returnValues" in nextStepOutput) {
168
+ const output = await this.agentExecutor._return(nextStepOutput, this.intermediateSteps, runManager);
169
+ if (this.runManager) {
170
+ await this.runManager.handleChainEnd(output);
171
+ }
172
+ await this.setFinalOutputs(output);
173
+ return output;
174
+ }
175
+ this.intermediateSteps = this.intermediateSteps.concat(nextStepOutput);
176
+ let output = {};
177
+ if (Array.isArray(nextStepOutput) && nextStepOutput.length === 1) {
178
+ const nextStep = nextStepOutput[0];
179
+ const toolReturn = await this.agentExecutor._getToolReturn(nextStep);
180
+ if (toolReturn) {
181
+ output = await this.agentExecutor._return(toolReturn, this.intermediateSteps, runManager);
182
+ if (this.runManager) {
183
+ await this.runManager.handleChainEnd(output);
184
+ }
185
+ await this.setFinalOutputs(output);
186
+ }
187
+ }
188
+ output = { intermediateSteps: nextStepOutput };
189
+ return output;
190
+ }
191
+ async _stop() {
192
+ const output = await this.agentExecutor.agent.returnStoppedResponse(this.agentExecutor.earlyStoppingMethod, this.intermediateSteps, this.inputs);
193
+ const returnedOutput = await this.agentExecutor._return(output, this.intermediateSteps, this.runManager);
194
+ await this.setFinalOutputs(returnedOutput);
195
+ return returnedOutput;
196
+ }
197
+ async _callNext() {
198
+ // final output already reached: stopiteration (final output)
199
+ if (this.finalOutputs) {
200
+ throw new Error(`Final outputs already reached: ${JSON.stringify(this.finalOutputs, null, 2)}`);
201
+ }
202
+ // timeout/max iterations: stopiteration (stopped response)
203
+ if (!this.agentExecutor.shouldContinueGetter(this.iterations)) {
204
+ return this._stop();
205
+ }
206
+ const nextStepOutput = await this._executeNextStep(this.runManager);
207
+ const output = await this._processNextStepOutput(nextStepOutput, this.runManager);
208
+ this.updateIterations();
209
+ return output;
210
+ }
211
+ }
212
+ exports.AgentExecutorIterator = AgentExecutorIterator;
9
213
  /**
10
214
  * Tool that just returns the query.
11
215
  * Used for exception tracking.
@@ -138,6 +342,9 @@ class AgentExecutor extends base_js_1.BaseChain {
138
342
  static fromAgentAndTools(fields) {
139
343
  return new AgentExecutor(fields);
140
344
  }
345
+ get shouldContinueGetter() {
346
+ return this.shouldContinue.bind(this);
347
+ }
141
348
  /**
142
349
  * Method that checks if the agent execution should continue based on the
143
350
  * number of iterations.
@@ -257,6 +464,149 @@ class AgentExecutor extends base_js_1.BaseChain {
257
464
  const finish = await this.agent.returnStoppedResponse(this.earlyStoppingMethod, steps, inputs);
258
465
  return getOutput(finish);
259
466
  }
467
+ async _takeNextStep(nameToolMap, inputs, intermediateSteps, runManager) {
468
+ let output;
469
+ try {
470
+ output = await this.agent.plan(intermediateSteps, inputs, runManager?.getChild());
471
+ }
472
+ catch (e) {
473
+ // eslint-disable-next-line no-instanceof/no-instanceof
474
+ if (e instanceof output_parser_js_1.OutputParserException) {
475
+ let observation;
476
+ let text = e.message;
477
+ if (this.handleParsingErrors === true) {
478
+ if (e.sendToLLM) {
479
+ observation = e.observation;
480
+ text = e.llmOutput ?? "";
481
+ }
482
+ else {
483
+ observation = "Invalid or incomplete response";
484
+ }
485
+ }
486
+ else if (typeof this.handleParsingErrors === "string") {
487
+ observation = this.handleParsingErrors;
488
+ }
489
+ else if (typeof this.handleParsingErrors === "function") {
490
+ observation = this.handleParsingErrors(e);
491
+ }
492
+ else {
493
+ throw e;
494
+ }
495
+ output = {
496
+ tool: "_Exception",
497
+ toolInput: observation,
498
+ log: text,
499
+ };
500
+ }
501
+ else {
502
+ throw e;
503
+ }
504
+ }
505
+ if ("returnValues" in output) {
506
+ return output;
507
+ }
508
+ let actions;
509
+ if (Array.isArray(output)) {
510
+ actions = output;
511
+ }
512
+ else {
513
+ actions = [output];
514
+ }
515
+ const result = [];
516
+ for (const agentAction of actions) {
517
+ let observation = "";
518
+ if (runManager) {
519
+ await runManager?.handleAgentAction(agentAction);
520
+ }
521
+ if (agentAction.tool in nameToolMap) {
522
+ const tool = nameToolMap[agentAction.tool];
523
+ try {
524
+ observation = await tool.call(agentAction.toolInput, runManager?.getChild());
525
+ }
526
+ catch (e) {
527
+ // eslint-disable-next-line no-instanceof/no-instanceof
528
+ if (e instanceof base_js_2.ToolInputParsingException) {
529
+ if (this.handleParsingErrors === true) {
530
+ observation =
531
+ "Invalid or incomplete tool input. Please try again.";
532
+ }
533
+ else if (typeof this.handleParsingErrors === "string") {
534
+ observation = this.handleParsingErrors;
535
+ }
536
+ else if (typeof this.handleParsingErrors === "function") {
537
+ observation = this.handleParsingErrors(e);
538
+ }
539
+ else {
540
+ throw e;
541
+ }
542
+ observation = await new ExceptionTool().call(observation, runManager?.getChild());
543
+ }
544
+ }
545
+ }
546
+ else {
547
+ observation = `${agentAction.tool} is not a valid tool, try another available tool: ${Object.keys(nameToolMap).join(", ")}`;
548
+ }
549
+ result.push({
550
+ action: agentAction,
551
+ observation,
552
+ });
553
+ }
554
+ return result;
555
+ }
556
+ async _return(output, intermediateSteps, runManager) {
557
+ if (runManager) {
558
+ await runManager.handleAgentEnd(output);
559
+ }
560
+ const finalOutput = output.returnValues;
561
+ if (this.returnIntermediateSteps) {
562
+ finalOutput.intermediateSteps = intermediateSteps;
563
+ }
564
+ return finalOutput;
565
+ }
566
+ async _getToolReturn(nextStepOutput) {
567
+ const { action, observation } = nextStepOutput;
568
+ const nameToolMap = Object.fromEntries(this.tools.map((t) => [t.name.toLowerCase(), t]));
569
+ const [returnValueKey = "output"] = this.agent.returnValues;
570
+ // Invalid tools won't be in the map, so we return False.
571
+ if (action.tool in nameToolMap) {
572
+ if (nameToolMap[action.tool].returnDirect) {
573
+ return {
574
+ returnValues: { [returnValueKey]: observation },
575
+ log: "",
576
+ };
577
+ }
578
+ }
579
+ return null;
580
+ }
581
+ _returnStoppedResponse(earlyStoppingMethod) {
582
+ if (earlyStoppingMethod === "force") {
583
+ return {
584
+ returnValues: {
585
+ output: "Agent stopped due to iteration limit or time limit.",
586
+ },
587
+ log: "",
588
+ };
589
+ }
590
+ throw new Error(`Got unsupported early_stopping_method: ${earlyStoppingMethod}`);
591
+ }
592
+ async *_streamIterator(
593
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
594
+ inputs) {
595
+ const agentExecutorIterator = new AgentExecutorIterator({
596
+ inputs,
597
+ agentExecutor: this,
598
+ metadata: this.metadata,
599
+ tags: this.tags,
600
+ callbacks: this.callbacks,
601
+ });
602
+ const iterator = agentExecutorIterator.streamIterator();
603
+ for await (const step of iterator) {
604
+ if (!step) {
605
+ continue;
606
+ }
607
+ yield step;
608
+ }
609
+ }
260
610
  _chainType() {
261
611
  return "agent_executor";
262
612
  }
@@ -2,11 +2,63 @@ import { BaseChain, ChainInputs } from "../chains/base.js";
2
2
  import { BaseMultiActionAgent, BaseSingleActionAgent } from "./agent.js";
3
3
  import { StoppingMethod } from "./types.js";
4
4
  import { SerializedLLMChain } from "../chains/serde.js";
5
- import { AgentAction, AgentFinish, AgentStep, ChainValues } from "../schema/index.js";
6
- import { CallbackManagerForChainRun } from "../callbacks/manager.js";
5
+ import { AgentAction, ChainValues, AgentFinish, AgentStep } from "../schema/index.js";
6
+ import { CallbackManagerForChainRun, Callbacks } from "../callbacks/manager.js";
7
7
  import { OutputParserException } from "../schema/output_parser.js";
8
- import { StructuredTool, Tool, ToolInputParsingException } from "../tools/base.js";
8
+ import { StructuredTool, ToolInputParsingException, Tool } from "../tools/base.js";
9
9
  import { Runnable } from "../schema/runnable/base.js";
10
+ import { Serializable } from "../load/serializable.js";
11
+ interface AgentExecutorIteratorInput {
12
+ agentExecutor: AgentExecutor;
13
+ inputs: Record<string, string>;
14
+ callbacks?: Callbacks;
15
+ tags?: string[];
16
+ metadata?: Record<string, unknown>;
17
+ runName?: string;
18
+ runManager?: CallbackManagerForChainRun;
19
+ }
20
+ export declare class AgentExecutorIterator extends Serializable implements AgentExecutorIteratorInput {
21
+ lc_namespace: string[];
22
+ agentExecutor: AgentExecutor;
23
+ inputs: Record<string, string>;
24
+ callbacks: Callbacks;
25
+ tags: string[] | undefined;
26
+ metadata: Record<string, unknown> | undefined;
27
+ runName: string | undefined;
28
+ private _finalOutputs;
29
+ get finalOutputs(): Record<string, unknown> | undefined;
30
+ /** Intended to be used as a setter method, needs to be async. */
31
+ setFinalOutputs(value: Record<string, unknown> | undefined): Promise<void>;
32
+ runManager: CallbackManagerForChainRun | undefined;
33
+ intermediateSteps: AgentStep[];
34
+ iterations: number;
35
+ get nameToToolMap(): Record<string, Tool>;
36
+ constructor(fields: AgentExecutorIteratorInput);
37
+ /**
38
+ * Reset the iterator to its initial state, clearing intermediate steps,
39
+ * iterations, and the final output.
40
+ */
41
+ reset(): void;
42
+ updateIterations(): void;
43
+ streamIterator(): AsyncGenerator<Record<string, unknown>, Record<string, unknown>, unknown>;
44
+ /**
45
+ * Perform any necessary setup for the first step
46
+ * of the asynchronous iterator.
47
+ */
48
+ onFirstStep(): Promise<void>;
49
+ /**
50
+ * Execute the next step in the chain using the
51
+ * AgentExecutor's _takeNextStep method.
52
+ */
53
+ _executeNextStep(runManager?: CallbackManagerForChainRun): Promise<AgentFinish | AgentStep[]>;
54
+ /**
55
+ * Process the output of the next step,
56
+ * handling AgentFinish and tool return cases.
57
+ */
58
+ _processNextStepOutput(nextStepOutput: AgentFinish | AgentStep[], runManager?: CallbackManagerForChainRun): Promise<Record<string, string | AgentStep[]>>;
59
+ _stop(): Promise<Record<string, unknown>>;
60
+ _callNext(): Promise<Record<string, unknown>>;
61
+ }
10
62
  type ExtractToolType<T> = T extends {
11
63
  ToolType: infer Tool;
12
64
  } ? Tool : StructuredTool;
@@ -77,6 +129,7 @@ export declare class AgentExecutor extends BaseChain<ChainValues, AgentExecutorO
77
129
  constructor(input: AgentExecutorInput);
78
130
  /** Create from agent and a list of tools. */
79
131
  static fromAgentAndTools(fields: AgentExecutorInput): AgentExecutor;
132
+ get shouldContinueGetter(): (iterations: number) => boolean;
80
133
  /**
81
134
  * Method that checks if the agent execution should continue based on the
82
135
  * number of iterations.
@@ -86,6 +139,11 @@ export declare class AgentExecutor extends BaseChain<ChainValues, AgentExecutorO
86
139
  private shouldContinue;
87
140
  /** @ignore */
88
141
  _call(inputs: ChainValues, runManager?: CallbackManagerForChainRun): Promise<AgentExecutorOutput>;
142
+ _takeNextStep(nameToolMap: Record<string, Tool>, inputs: ChainValues, intermediateSteps: AgentStep[], runManager?: CallbackManagerForChainRun): Promise<AgentFinish | AgentStep[]>;
143
+ _return(output: AgentFinish, intermediateSteps: AgentStep[], runManager?: CallbackManagerForChainRun): Promise<AgentExecutorOutput>;
144
+ _getToolReturn(nextStepOutput: AgentStep): Promise<AgentFinish | null>;
145
+ _returnStoppedResponse(earlyStoppingMethod: StoppingMethod): AgentFinish;
146
+ _streamIterator(inputs: Record<string, any>): AsyncGenerator<ChainValues>;
89
147
  _chainType(): "agent_executor";
90
148
  serialize(): SerializedLLMChain;
91
149
  }